Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally set dynamic pug variables

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?

like image 707
Get Off My Lawn Avatar asked Dec 04 '17 05:12

Get Off My Lawn


1 Answers

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
like image 144
Soviut Avatar answered Oct 12 '22 04:10

Soviut