Node.js – Expressjs中间件来扩展res.render

我想知道是否有一个内置的方式来扩展Express.js的res.render函数,因为我想传递一个默认的“本地”设置到每个模板呈现。 目前我已经编写了一个小的中间件,使用underscore.js的扩展函数来合并默认的“本地”和那个特定的模板:

app.use(function(req, res, next){ res.render2 = function (view, locals, fn) { res.render(view, _.extend(settings.template_defaults, locals), fn); }; next(); }); 

有一个更好的方法吗?

app.locals可能是你要找的东西:

 app.locals(settings.template_defaults); 

Express与res.localsres.render ,已经能够为您合并价值:

 // 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({ // eg session: req.session }); next(); }); // and locals specific to the route app.get('...', function (req, res) { res.render('...', { // ... }); }); 
 res.locals or app.locals is for this exact purpose.