Node.js - Expressjs中间件扩展res.render

时间:2012-12-22 04:35:07

标签: node.js express middleware

我想知道是否有内置的方法来扩展Express.js的res.render函数,因为我想将一组默认的“locals”传递给每个呈现的模板。目前我编写了一个小型中间件,它使用underscore.js的扩展函数来合并默认的“locals”和特定于该模板的“locals”:

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

有更好的方法吗?

2 个答案:

答案 0 :(得分:7)

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

app.locals(settings.template_defaults);

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

// 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 :(得分:3)

res.locals or app.locals is for this exact purpose.