默认或继承{{sections}}在node.js中使用Hogan

时间:2015-01-16 23:01:46

标签: javascript node.js hogan.js

当我调用res.render时,有没有办法总是对部分使用相同的变量?例如:

res.render('index', {
        layout: 'layouts/dashboard/slim',
        partials:{
          partial_one: "path/to/partial_one.hjs",
          partial_two: "path/to/partial_two.hjs"
        },
        title: 'Dashboard',
        section_one: foo,
        section_two: bar
      });

我希望res.render始终将这两个部分与foo和bar相关联,而不必每次都将它们包含在调用中。这可能吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

创建customRender:

renderCustom('index', {
  layout: 'layouts/dashboard/slim',
  title: 'Dashboard',
  section_one: foo,
  section_two: bar
});

function renderCustom(name, object) {
  object.partials = {};
  object.partials.partial_one =  "path/to/partial_one.hjs";
  object.partials.partial_two =  "path/to/partial_two.hjs";

  res.render(name, object);
}

或者,您可以热修补渲染功能。

app.use(function (req, res, next) {
  var render = res.render;
  res.render = function (view, locals, cb) {
    if (typeof locals == 'object') {
        locals.partials = {};
        locals.partials.partial_one = "path/to/partial_one.hjs";
        locals.partials.partial_two = "path/to/partial_two.hjs";
    }
      render.call(res, view, locals, cb);
};
  next();
});