快递中间件来为所有app.get()填充一个Jadevariables

我有一个Jade文件,我所有的模板扩展名为layout.jade。 其中我希望能够有一个注销button,如果用户当前login(这是跟踪req.session)。

所以layout.jade会有类似的东西,

-if (loggedin) a.navButton(href="/logout") Log Out 

页面的路线看起来像,

 app.get("/foo", function(req, res) { res.render("foo", {loggedin: req.session.isValidUser}); }); 

事情是,我不想在每一个路线手动填写loginvariables。 有没有一种方法可以使用Express中间件来自动设置发送到res.render的对象的一些默认选项? 还是有更好的方法来做到这一点?

基本上我问我怎样才能有一些总是发送到模板的variables,以及通过在路由中手动设置某些自定义variables在某些模板中可用。

看来这实际上是一个logging的function,我只是很难find,除非任何人有更好的方法来做到这一点; 从最新的Express文档中 ,

app.locals :应用程序本地variables被提供给应用程序内的所有模板 。 这对于为模板提供帮助函数以及应用程序级别的数据非常有用。

所以在我的login成功函数中,

 req.session.username = profile.username; app.locals.username = profile.username; 

我的注销function,

 app.get('/logout', function (req, res) { delete app.locals.username; req.session.destroy(); res.redirect('/login'); }); 

最后在layout.jade /我的所有模板中,

 - if(username) a.navButton(href="/logout") Logout 

如果在/login路由中设置了res.locals.loggedin ,就像hexacyanidebuild议的那样,这个本地在/foo路由中将不可用。 每次请求清除res.locals

你可以尝试把这个以上的其他路线:

 app.all('*', function(req, res, next){ if(req.user){ res.locals.loggedin = true; res.locals.currentuser = req.user; }; next(); }); 

很确定,如果您在路由期间修改了res.locals.currentuser ,那么您之前设置的res.locals.currentuser将不会更新为新的req.user 。 但不确定。

实际上,我为每个渲染模板的页面使用自定义render函数,如下所示:

 function myRender(templateName){ return function(req, res){ res.locals.currentuser = req.user || null; res.render(templateName); }; }; 

我这样使用它:

 app.get('/foo' , function(req, res, next){ res.locals.bar = req.query['bar'] || ""; console.log('passing request to myRender middleware'); next(); } , myRender('foo-jade-template') ) 

这样做的好处是只需要设置res.locals.currentuser就可以渲染一些东西,而不是在执行路由之前。 所以如果我改变了req.user ,保证在渲染的时候有最新的版本。

在Express源代码中有一行代码对你来说非常有用:

 // merge res.locals options._locals = self.locals; 

因此,当你运行res.render() ,Express也会将存储在res.locals任何本地res.locals传递给渲染器。 因此,您所要做的就是将res.locals.loggedin设置为true,然后照常运行res.render()

 app.get('/login', function(res, res) { res.locals.loggedin = true; }); app.get('/foo', function(req, res) { res.render('foo', {}); });