variables in expressjs views
I want to make session variables (or any others) usable in the views without repeating myself all over again.
I came up with this:
res.render('index', viewVariables(req, res, params, {});
And the viewVariables
function:
function viewVariables(re开发者_运维百科q, res, params, options) {
var returnObject = options || {locals:{}};
var locals = {
currentUser: req.currentUser ? req.currentUser : false
};
returnObject.locals = mergeObjects(locals, returnObject.locals, true);
return returnObject;
};
Thats not working in the latest expressjs version (different render method).
Is there a simpler or more elegent solution for that? (well I'm sure there is!)
Have you looked at dynamichelpers?
From the website:
app.dynamicHelpers(obj)
Registers dynamic view helpers. Dynamic view helpers are simply functions which accept req, res, and are evaluated against the Server instance before a view is rendered. The return value of this function becomes the local variable it is associated with.
app.dynamicHelpers({
session: function(req, res){
return req.session;
}
});
Most of the times I like to make it a function instead. This way it will be only called when you call the function in your views.
Express v2.x
app.dynamicHelpers({
session: function(req, res){
return req.session;
}
});
Express v.3
app.use(function(req, res) {
res.locals.session = req.session;
});
精彩评论