2012-09-30 11 views
6

मैं एक्सप्रेस 2 में प्रत्येक पृष्ठ पर कुछ चर सेट करने के लिए गतिशील हेल्पर का उपयोग कर रहा था। अब वे चले गए हैं और मुझे यकीन नहीं है कि यह कैसे करें। एक्सप्रेस 3 के साथ ऐसा कुछ करने का सबसे अच्छा तरीका क्या है?एक्सप्रेस 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 
+0

https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x – supernova

+0

हां मैंने देखा। यह वास्तव में प्रश्न का उत्तर नहीं देता है हालांकि – Pardoner

उत्तर

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

एक्सप्रेस 3.x app.locals के लिए चाल है! – Zugwalt

2

आप अपने मार्ग कॉल करने से पहले निम्न जैसे कुछ मिडलवेयर चाहेगा:

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

मुझे लगता है कि आपका कोड '' 'app.use (फ़ंक्शन (req, res, next) { res.locals.user = {उपयोगकर्ता नाम: 'test'}; अगला होना चाहिए(); }); '' ' – Yalamber

संबंधित मुद्दे