简体   繁体   English

Express.js:在请求挂钩中为EJS添加变量

[英]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: 我想在每个请求上呈现视图时添加一些EJS使用的变量,就像将它们与render函数中的变量一起添加一样:

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: 如果仅在此处将变量设置为请求对象,则可以在路由中获取该变量并将其发送到render函数中,如下所示:

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 更多信息: https : //github.com/expressjs/session

I sometimes use res.locals if the following: 如果以下情况,我有时会使用res.locals

  • 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 这样,您不必在每条路线中都设置变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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