I began using node.js+express combo very recently and I stumbled at a need to use dynamicHelpers not only in my views but also inside my routes setup (routes/index.js in default express config). Should I use some different pattern?
app.js
app.dynamicHelpers({
translate : function(req, res) {
return translate;
},
language : function(req, res) {
return req.session.language || "en";
},
});
Below I would like to have a convenient access to whatever I set for my dynamicHelpers because in my mind it is the same context .. so why set it up two times?
var routes = {};
routes.index = function(req, res) {
res.render('index', {
title : 'My webpage',
categories : categoryPositions,
referrer : req.header("Referrer"),
languages : ["pl", "en", "de"],
<----- here I would like to use my dynamicHelpers (for example translate)
})
};
I know I can pass my data in many ways but I do not want to repeat my code
and want to set up the common context only once and as cleanly as polssible. I welcome any criticism and good advice!
So actually the solution is to use not yet released express 3.0, modify:
npm install -g express@3.0Follow https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x , http://www.devthought.com/code/use-jade-blocks-not-layouts/
The new express simplified dynamicHelpers to the use of
res.localswhich are both available in the routes setup and then bound to the view.Example:
In the routes setup I can now access both
res.locals.languageandres.locals.translate.In my views I simply can use
translate('something').