我的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'
});
});
并且,要呈现的new.jade
文件如下所示:
...
h1 #{application.name}
...
当我在控制台上打印req.session.application
对象时,它打印正常,但是当呈现new.jade
时,它没有从会话中找到application
对象并认为它是null
。我错过了什么?
答案 0 :(得分:0)
为模板提供变量
res.render('new', {
// <- here is all variables that will be available in jade
title: 'Add a new intent',
application: req.session.application
});
答案 1 :(得分:0)
我最终编写了一个快速的midleware函数,用于检查会话中是否存在application
对象,并将其添加到会话对象中,如下所示。通过此更改,我无需在呈现Jade视图时将req.session.application
对象传递给res.render()
方法。
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();
}
});
来自Jade视图的片段:
...
h1 #{application.name}
...