Vladimir37
Vladimir37

Reputation: 568

Special parameter for render in Express

I use Jade for rendering templates. It looks like this:

res.render('template_name', {var1: 'One', var2: 'Two'})

But I need that each render add one parameter, which is the result of the function. Example. I write

res.render('template_name', {var1: 'One', var2: 'Two'})

But it reads like

res.render('template_name', {var1: 'One', var2: 'Two', var3: func()})

How to do it?

Upvotes: 0

Views: 120

Answers (1)

Renato Gama
Renato Gama

Reputation: 16519

You will have to add a middleware before all routes that you want to access var3, like this;

function populateLocals(req, res, next){
  res.locals.var3 = function() {
    return "alalao";
  };

  next();
}

app.use(populateLocals);

You can add specific values to locals on a route basis by doing it individually like this;

app.get('/', populateLocals, function(req, res, next) {
    res.render('foo', {a: 1, b: 2});
});

app.get('/whatever', populateLocals, function(req, res, next) {
    res.render('foo', {a: 1, b: 2});
});

Also, have a look at this other question

Upvotes: 1

Related Questions