简体   繁体   中英

Express.js: Adding variables for EJS in request hook

I want to add some variables to be used by EJS when rendering a view on each request, as if adding them along with the variables in the render function:

res.render('view', {data: {my: 'object'}});

I have this function which I'm using as my request hook:

app.use('/*', function(req, res, next) {
  function after_request() {
    console.log('called after');
  }
  function before_request() {
    console.log('called before');
  }
  before_request();
  res.on('finish', after_request);
  next();
});

Which is working fine:

called before
GET /url/param 304 30.762 ms - -
called after

If I just set the variable to the request object here I can get the variable in my route and send it in the render function like so:

var variable = req.variable;
res.render('view', {data: {my: 'object', my: variable}});

But I would like to be able to not have to set this variable like this in every route.

Is there a way to do this?

You could use sessions, they allow you to share values over all the requests of a user session.

More info: https://github.com/expressjs/session

I sometimes use res.locals if the following:

  • I don't want to use sessions or persist same value from page to page, but rather it get's set each time the middleware is called

  • The variable is always named the same

  • I use pug/jade views

Then you can:

app.use(function(req, res, next){
  res.locals.variable = "some content";
  next();
})

and in your view

extends layout

block content
  p= variable //'some content'

That way you don't have to set the variable in every route

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM