繁体   English   中英

预编译模板中的Hogan.js局部

[英]Hogan.js partials in pre-compiled template

是否可以在已编译的模板中包含局部变量? 由于在编译对象中引用了部分名称,因此看起来似乎有可能,但是我不知道如何使它起作用。

我正在服务器端(node.js)上预编译Hogan.js模板,并使其在客户端上可用。 这是模板的片段:

<ul class="log-{{id}}">
  {{#entries}}
    {{> entry}}
  {{/entries}}
</ul>

编译完模板后,我会在对象中看到一个带有<entry0键的partials属性。

我可以使用以下方法在客户端上渲染模板:

var data = {id: 11, entries: [{ id: 1, name: 'Entry 1'}, {id: 2, name: 'Entry 2'}]};

template = new Hogan.Template(compiledTemplate);
template.render(data);

该模板可以很好地呈现,但是在{{#entries}} {{/entries}}块中什么也没有。 部分本身也已预编译,可在客户端使用。 我试图通过几种不同的方式来传递它,包括:

 template.render(data, {partials: { entry: compiledEntryTemplate }});

所有迹象似乎都表明这应该是可能的,但我只是无法弄清楚,也找不到任何指出如何操作的文档。 我正在使用Hogan.js 3.0.1

设法弄清楚了。 以下内容将使已编译的部分文件可以在已编译的模板中访问。

 template.render(data, { entry: new Hogan.Template(compiledEntryTemplate) });

@TJ,您可以看看hogan.js测试套件( https://github.com/twitter/hogan.js/blob/master/test/index.js )。 在那里,您将找到一个名为“ Partial Basic”的测试用例,其内容为

var partialText = "this is text from the partial--the magic number {{foo}} is from a variable";
  var p = Hogan.compile(partialText);

  var text = "This template contains a partial ({{>testPartial}})."
  var t = Hogan.compile(text);

  var s = t.render({foo: 42}, {testPartial: p});
  is(s, "This template contains a partial (this is text from the partial--the magic number 42 is from a variable).", "partials work");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM