Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to render common variables from app.js to all routes in express

In my Node.js application some variables that render or every route are common.There are around 4-5 variables which render on every route. And I have around 20 routes.

Currently I am doing passing those variables in every route in res.render

Is there a method by which I can pass these common variables in some place '(eg:app.js)` which is being used by every route, so that I can clean up my code a bit.

I use express.js for node and handlebars for template.

EDIT:I think I should explain a bit more

res.render('abc', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

-------------------------------------
another route
res.render('xyz', {
                        commonitem1: 'one',
                        commonitem2: 'two',
                        ...
                   });

I want to avoid this repeating in my every routes and want to render it from a common place.

like image 900
zamil Avatar asked Mar 13 '15 07:03

zamil


1 Answers

For session or request dependent values you can store those common values in a global variable and then use them directly in res.render. To do that you have following options

  • Use app.use to store values :

In your app.js add a middleware which does this for you. Remember to write this middleware before any other routes you define because middleware functions are executed sequentially.

app.use(function(req, res, next){
    res.locals.items = "Value";
    next();
});
//your routes follow
app.use(‘/’, home);

In your routes you can place items directly in res.render like:

res.render('layout', {title: 'My awesome title',view: 'home', item :res.locals.items });
  • Use express-session to store values :

If you have express-session installed you can save some data in req.session.item and place them in any route like:

res.render('layout', {title: 'My awesome title',view: 'home', item :req.session.items });
like image 154
Sumit Sinha Avatar answered Oct 09 '22 01:10

Sumit Sinha