如何将数据传递到Express 3中的每个视图?

我正在使用dynamicHelpers在Express 2的每个页面上设置一些variables。现在,他们走了,我不知道该怎么做。 使用Express 3做这种事情的最佳方式是什么?

app.js

app.dynamicHelpers( require('dynamicHelpers') ) 

dynamicHelpers.js

 exports.user = function(req, res) { return req.user || {}; } exports.message = function(req, res) { return req.flash.message || {}; } 

在veiw.jade

 h1= user.username 

       

网上收集的解决方案 "如何将数据传递到Express 3中的每个视图?"

中间件的例子

 var app = require('express')() , jade = require('jade') app.set('views', __dirname + '/views') app.set('view engine', 'jade') app.use(function(req,res,next){ res.locals.user = { name : "test" } next() }) app.get('*',function(req,res){ res.render('index.jade') }) app.listen('8001') 

index.jade

 !!! 5 html body div hello #{user.name} 

使用req.flash尝试:

 var app = require('express')() , jade = require('jade') app.set('views', __dirname + '/views') app.set('view engine', 'jade') app.use(require('connect-flash')()) // Expose the flash function to the view layer app.use(function(req, res, next) { res.locals.flash = req.flash.bind(req) next() }) app.get('*',function(req,res){ res.render('index.jade') }) app.listen('8001') 

更新我的答案,还没有迁移到3.0,在视图选项下的https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x

 The "view options" setting is no longer necessary, app.locals are the local variables merged with res.render()'s, so app.locals.pretty = true is the same as passing res.render(view, { pretty: true }). 

在路由呼叫之前,你会需要一些像下面这样的中间件:

 app.use(function(req,res,next){ res.locals.user = {username: 'test'}; next(); });