8

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

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

有一个更好的方法吗?

4

2 回答 2

7

app.locals可能是您正在寻找的:

app.locals(settings.template_defaults);

res.locals和一起res.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('...', {
        // ...
    });
});
于 2012-12-22T07:19:39.310 回答
3
res.locals or app.locals is for this exact purpose.
于 2012-12-22T05:06:02.613 回答