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

时间:2012-09-30 02:37:32

标签: node.js express

我正在使用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 || {};
}

in veiw.jade

h1= user.username

2 个答案:

答案 0 :(得分:8)

中间件示例

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 }).

答案 1 :(得分:2)

在路由呼叫之前,您需要一些类似以下的中间件:

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