8

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?

1
  • what are you trying to do? Commented Dec 22, 2012 at 7:08

2 Answers 2

7

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('...', {
        // ...
    });
});
1
  • It's res.locals, though link is okay (can't edit 1 symbol). Commented Dec 22, 2012 at 10:43
3
res.locals or app.locals is for this exact purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.