Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is meaning of locals in res.render (node.js)?

what is difference between below two code block in Node.JS (express + ejs)?

res.render('demo', {locals:{"variable":data}});

AND

res.render('demo', {"variable":data});

When to use which one? can any one please help me out in this.

like image 681
Hemang Avatar asked Nov 20 '25 09:11

Hemang


1 Answers

The correct way of passing variables to the view is the following

res.render('demo', {"variable":data});

Then you have an object res.locals which you can append data and it will be passed to the view.

For example, if you have a middleware for the authentication, you can set the auth variables even before the request arrives in your route.

app.use(function(req, res, next){
    res.locals.user = req.user;
    res.locals.authenticated = ! req.user.anonymous;
    next();
});
like image 154
DevAlien Avatar answered Nov 22 '25 00:11

DevAlien



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!