简体   繁体   English

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

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

Is it possible to have partials within a compiled template? 是否可以在已编译的模板中包含局部变量? It would appear like it's possible, as the partial name is referenced in the compiled object, but I have no idea how to get it to work. 由于在编译对象中引用了部分名称,因此看起来似乎有可能,但是我不知道如何使它起作用。

I'm pre-compiling Hogan.js templates on the server side (node.js) and making them available on the client side. 我正在服务器端(node.js)上预编译Hogan.js模板,并使其在客户端上可用。 Here's a snippet of the template: 这是模板的片段:

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

Once that template is compiled, I see a partials attribute in the object with a key of <entry0 编译完模板后,我会在对象中看到一个带有<entry0键的partials属性。

I'm able to render the template on the client side using the following: 我可以使用以下方法在客户端上渲染模板:

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

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

The template renders just fine, but nothing within the {{#entries}} {{/entries}} block. 该模板可以很好地呈现,但是在{{#entries}} {{/entries}}块中什么也没有。 The partial itself is also pre-compiled and available on the client side. 部分本身也已预编译,可在客户端使用。 I've tried to pass that in several different ways, including: 我试图通过几种不同的方式来传递它,包括:

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

All signs seem to point like this should be possible, but I just can't figure it out or find documentation anywhere that points out how to do it. 所有迹象似乎都表明这应该是可能的,但我只是无法弄清楚,也找不到任何指出如何操作的文档。 I'm using Hogan.js 3.0.1 我正在使用Hogan.js 3.0.1

Managed to figured it out. 设法弄清楚了。 The following will make the compiled partial accessible in your compiled template. 以下内容将使已编译的部分文件可以在已编译的模板中访问。

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

@TJ you can take a look at hogan.js test suite ( https://github.com/twitter/hogan.js/blob/master/test/index.js ). @TJ,您可以看看hogan.js测试套件( https://github.com/twitter/hogan.js/blob/master/test/index.js )。 There you'll find out a test case called "Partial Basic" which reads 在那里,您将找到一个名为“ 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