我正在使用dynamicHelpers在Express 2的每个页面上设置一些变量.现在它们已经消失,我不知道该怎么做.使用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
解决方法
中间件示例
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') app.use(require('connect-flash')()) // Expose the flash function to the view layer app.use(function(req,next) { res.locals.flash = req.flash.bind(req) next() }) app.get('*',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 }).