Get name of template inside a pugjs template

135 Views Asked by At

I'm rendering my pages with pugJS like this:

res.render('test',renderVars)

This render uses a layout, in which I need to get the 'test' string. My question is: how can I get the 'test' string so that I can use it in my layout? I could put a new variable in 'renderVars' but I'm sure there is a better solution.

In other words: how can I get the name of a template inside this template? Something like #{templatename} for example?

Thanks in advance!

1

There are 1 best solutions below

2
Marcia Ong On

I'm afraid you can't do so. res.render 1st parameter is rendering a view template not mean to store data. You could set the 'test' in renderVars or you can add it in session and will be able to use it in your layout.

Add this code into your app.js before the routes and after session settings

//inject session into res.locals so can be rendered in UI
app.use(function (req, res, next) {
  if (req.session.message) {
    res.locals.message = req.session.message;
    delete req.session.message;
  }
  res.locals.session = req.session;

  next();
});

In the view template you can access the res.locals.session data by using

#{session.theAttributeYouWant)