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.
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>
精彩评论