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!
functions.js
module.exports = {
translate : function(req, res) {
return translate;
},
language : function(req, res) {
return req.session.language || "en";
},
};
helpers.js
var functions = require('./functions');
app.dynamicHelpers({
translate : functions.translate,
language : functions.language
});
Depending on what you need you can also write the helpers like this
var functions = require('./functions');
app.dynamicHelpers( functions );
routes.js
var functions = require('./functions');
var routes = {
index: function(req, res) {
res.render('index', {
title : 'My webpage',
categories : categoryPositions,
referrer : req.header("Referrer"),
languages : ["pl", "en", "de"],
stuff: functions.translate(req, res) // <----- here I would like to use my dynamicHelpers (for example translate)
})
}
};
So actually the solution is to use not yet released express 3.0, modify:
npm install -g express@3.0
Follow 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.locals
which are both available in the routes setup and then bound to the view.
Example:
// app.
app.locals.use(function(req, res) {
var language = req.session.language || "en";
res.locals.language = language;
res.locals.translate = function(clause) {
return translate(clause, language);
};
});
In the routes setup I can now access both res.locals.language
and res.locals.translate
.
In my views I simply can use translate('something')
.