Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express + EJS - passing arguments to EJS view

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?

like image 560
Uri Lukach Avatar asked Dec 06 '25 21:12

Uri Lukach


1 Answers

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.

like image 71
peteb Avatar answered Dec 09 '25 09:12

peteb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!