Globally set dynamic pug variables
Asked Answered
D

1

7

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?

Dendriform answered 4/12, 2017 at 5:0 Comment(0)
D
15

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
Daugherty answered 4/12, 2017 at 5:6 Comment(1)
That is exactly what I was looking for!Dendriform

© 2022 - 2024 — McMap. All rights reserved.