I am using express and pug, there are some values that I would like to pass to pug on every request, for example: req.session
and req.path
. Passing these values to the render()
method every time just seems too redundant.
So instead of doing something like this:
app.get('/', (req, res) => {
res.render('home', {session: req.session})
})
app.get('/profile', (req, res) => {
res.render('profile', {session: req.session})
})
The more routes that get added, the more of those items I need to manage. Is there a global way that I can set them once other than app.locals
so they are unique per request?
You can set variables that are available to every template on each request using a bit of custom middleware and locals
. This same approach works for all templating systems that Express can use, not just Pug.
Put the following before your routes.
app.use((req, res, next) => {
res.locals.session = req.session
next()
})
Then in your template you can call it like this.
h3= session.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With