Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data to every view in Express 3?

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
like image 982
Pardoner Avatar asked Sep 30 '12 02:09

Pardoner


1 Answers

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 }).
like image 194
supernova Avatar answered Nov 15 '22 00:11

supernova