简体   繁体   English

Express + EJS - 将参数传递给EJS视图

[英]Express + EJS - passing arguments to EJS view

I'm rather new to Node.js/Express/EJS. 我是Node.js / 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. 我最近注意到,当我将参数从Express请求处理程序传递到EJS视图并省略参数名称时,它会根据变量名称创建一个名称。 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 } tells the V8 engine to assign the property products the value of the variable products that is in scope. { products }告诉V8引擎为属性products分配范围内变量products的值。 This is called Object Literal Property Value Shorthand and is a feature of ES6. 这称为对象文字属性值简写 ,是ES6的一个特性。

{ products: products } is the long-form way to create an object in ES6 and the only way in any version prior to ES6. { products: products }是在ES6中创建对象的长形方式,也是ES6之前的任何版本的唯一方式。

As long as your Node version supports the shorthand you can use it. 只要您的Node版本支持简写,您就可以使用它。 Its all about preference and readability, there is no right or wrong way here. 这完全取决于偏好和可读性,这里没有正确或错误的方法。

Both codes are cpmpiled to the same result. 两个代码都被cpmpiled到相同的结果。 The first version is suggested by linter because it is shortener and readable. 第一个版本是由linter建议的,因为它更简洁,更易读。

Please learn JavaScript style guide, there are a lot of guides, eg airbnb, Google, etc. 请学习JavaScript风格指南,有很多指南,例如airbnb,Google等。

I recommend airbnb here. 我在这里推荐airbnb。 https://github.com/airbnb/javascript https://github.com/airbnb/javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM