Reputation: 1928
I'd like to know if there is a built in way to extend Express.js's res.render function because, I'd like to pass a default set of "locals" to every template that is rendered. Currently I've written a small middleware that uses underscore.js's extend function to merge the default "locals" and the ones specific for that template:
app.use(function(req, res, next){
res.render2 = function (view, locals, fn) {
res.render(view, _.extend(settings.template_defaults, locals), fn);
};
next();
});
Is there a better way to do this?
Upvotes: 8
Views: 3349
Reputation: 123453
app.locals
is likely what you're looking for:
app.locals(settings.template_defaults);
Along with res.locals
and res.render
, Express is already capable of merging the values for you:
// locals for all views in the application
app.locals(settings.template_defaults);
// middleware for common locals with request-specific values
app.use(function (req, res, next) {
res.locals({
// e.g. session: req.session
});
next();
});
// and locals specific to the route
app.get('...', function (req, res) {
res.render('...', {
// ...
});
});
Upvotes: 7