简体   繁体   English

在JADE中访问会话变量

[英]Accessing session variable in JADE

My GET /new end point looks like this: 我的GET /new端点如下所示:

router.get('/new', function(req, res) {
  console.log(JSON.stringify(req.session.application)); //<-- This prints FINE

  res.render('new', { 
    title: 'Add a new intent'
  });
});

And, the new.jade file to be rendered looks like: 并且,要呈现的new.jade文件如下所示:

...
h1 #{application.name}
...

When I print the req.session.application object on the console, it prints fine, but when the new.jade is rendered, it does not find the application object from the session and thinks it is null . 当我在控制台上打印req.session.application对象时,它可以正常打印,但是在呈现new.jade时,它没有从会话中找到该application对象,并认为它为null What am I missing? 我想念什么?

Provide variable to template 提供模板变量

res.render('new', { 
  // <- here is all variables that will be available in jade
  title: 'Add a new intent',
  application: req.session.application
});

I ended up writing a quick midleware function that checks if the application object exists in the session and adds that to the session object like below. 我最终编写了一个快速的中间件函数,该函数检查会话中是否存在application对象,并将其添加到会话对象中,如下所示。 With this change, I don't need to pass the req.session.application object to the res.render() method while rendering a Jade view. 进行此更改后,在渲染Jade视图时,无需将req.session.application对象传递给res.render()方法。

Middleware in app.js: app.js中的中间件:

app.use(function(req, res, next) {

  if (req.session && req.session.application) {
    mongoose.model('Application').findOne({ _id: req.session.application._id }, function(err, application) {
      if (application) {
        req.application = application;
        req.session.application = application;  //refresh the session value
        res.locals.application = application;
      }
      // finishing processing the middleware and run the route
      next();
    });
  } else {
    next();
  }
});

Snippet from Jade view: 玉视图中的摘录:

...
h1 #{application.name}
...

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

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