Express + EJS-将参数传递给EJS视图 [英] Express + EJS - passing arguments to EJS view

查看:501
本文介绍了Express + EJS-将参数传递给EJS视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node.js/Express/EJS很陌生.

I'm rather new to Node.js/Express/EJS.

我最近注意到,当我将参数从Express请求处理程序传递到EJS视图并省略参数名称时,它会基于变量名称创建一个名称.因此,例如,在下面的代码中,

I've recently noticed that when I'm passing arguments from an Express request handler to an EJS view and omit the argument name it creates a name based on the variable name. So, for example, in the code below,

//server.js
var express = require('express'); 
var app = express();

app.set('view engine', 'ejs');

app.get('/', function(req, res){ 
   var products = [
        { name: 'Tennis Ball', price: 10 },
        { name: 'Basketball', price: 20 }
    ];    

    res.render('index', {products});
});

 app.listen(8080);

//index.ejs
<ul>
<% products.forEach(function(product){ %>
<%= product.name %>
<% })%>
</ul>

传递的参数将称为产品",并且视图将能够很好地对其进行迭代.我认为,为了提高代码的可读性,我应该改为放置以下行:

The argument passed will be called "products" and the view will be able to iterate it well. I assume, for better code readability, I should have placed this line instead:

res.render('index', {products : products});

我想知道是否可以同时使用这两种技术?

I wonder if that's okay to use both techniques?

推荐答案

两者之间的区别仅在于您如何定义对象及其属性.

The difference between the two is just how you're defining your object and its properties.

{ products }告诉V8引擎为属性products分配范围内的变量products的值.这称为对象文字属性值速记,这是ES6的功能.

{ products } tells the V8 engine to assign the property products the value of the variable products that is in scope. This is called Object Literal Property Value Shorthand and is a feature of ES6.

{ products: products }是在ES6中创建对象的长格式,而在ES6之前的任何版本中都是 only 方法.

{ products: products } is the long-form way to create an object in ES6 and the only way in any version prior to ES6.

只要您的Node版本支持速记,就可以使用它.都是关于偏好和可读性的,这里没有对与错的方法.

As long as your Node version supports the shorthand you can use it. Its all about preference and readability, there is no right or wrong way here.

这篇关于Express + EJS-将参数传递给EJS视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆