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
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 }).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With