Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js / Express make variable available in layout on all routes

Once a user has logged in, I want to display their username in the header, which is currently part of layout.jade. Their details are in req.currentUser but req isn't accessible from the layout.

I know I can do the following for each of the render calls in my routes:

res.render('help', {
    locals: { currentUser: req.currentUser }
});

But it seems there must be a better way than adding { currentUser: req.currentUser } into the locals every single one of my routes.

I'm still a Node newbie, so apologies if this is a stupid question.

like image 993
benui Avatar asked Aug 30 '11 12:08

benui


People also ask

How do I create a global variable in Express?

To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.) //we can now access 'app' without redeclaring it or passing it in... /* * GET home page.

What function arguments are available to Express js route?

The arguments available to an Express. js route handler function are: req - the request object. res - the response object.


1 Answers

You need to use a dynamic helper. It is a function that is passed the request and response objects, just like any route or middleware, and can return data specific to the current request. (including session data)

So, in app.js:

app.dynamicHelpers({
  currentUser: function (req, res) {
    return req.currentUser;
  }
});

and in your template:

<div><%= currentUser %></div>
like image 135
Dominic Barnes Avatar answered Oct 16 '22 13:10

Dominic Barnes