I'm rather new to 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. 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. This is called Object Literal Property Value Shorthand and is a feature of ES6.
{ products: products }
is the long-form way to create an object in ES6 and the only way in any version prior to ES6.
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.
Both codes are cpmpiled to the same result. The first version is suggested by linter because it is shortener and readable.
Please learn JavaScript style guide, there are a lot of guides, e.g. airbnb, Google, etc.
I recommend airbnb here. https://github.com/airbnb/javascript
来源:https://stackoverflow.com/questions/37665825/express-ejs-passing-arguments-to-ejs-view