Reputation: 1111
I was using dynamicHelpers to set some variables on every page in Express 2. Now that they're gone and I'm not sure how to do it. What is the best way to do something like this with 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
Upvotes: 6
Views: 8135
Reputation: 3883
middleware example
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}
to use req.flash try:
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')
updated my answer, haven't migrated to 3.0 yet, at https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x under View options:
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 }).
Upvotes: 10
Reputation: 41587
You would want some middleware like the following before your route calls:
app.use(function(req,res,next){
res.locals.user = {username: 'test'};
next();
});
Upvotes: 2