开发者

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

开发者 https://www.devze.com 2023-03-31 13:41 出处:网络
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 th

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消