8

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.

benui
  • 6,440
  • 5
  • 34
  • 49

1 Answers1

9

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>
Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
  • 3
    'app.dynamicHelpers' seem to be deprecated in express v3 and replaced with 'app.use' – 828 Mar 04 '13 at 05:15
  • 2
    For those like me who will stumble into this answer a few years later, here's what you need to look at: http://stackoverflow.com/questions/11580796/migrating-express-js-2-to-3-specifically-app-dynamichelpers-to-app-locals-use – maksimov Nov 19 '15 at 10:34