我如何在每个助手的车把内使用其他模板值?

How can I use other template values inside a handlebar each helper?

我有 json 个包含数组的数据块(示例)

var data = { firstName: "Alan", lastName: "Johnson", list: [1,2,3] };

我想使用 #each 语法遍历数组中的项目并为每个项目创建一个字符串,其中包含数组中的项目以及我传入的另一条 json 数据.这就是我正在尝试的:

var ui  = "<p>{{lastName}}, {{firstName}}</p>";
ui  = ui + "{{#each list}}";
ui  = ui + "    {{this}} - {{ firstName }}";
ui  = ui + "{{/each}}";

var template = Handlebars.compile(ui);

console.log(template(data));

但它没有输出我所期望的。我明白了(错误):

<p>Johnson, Alan</p>    1 -     2 -     3 -

但我想看这个:

<p>Johnson, Alan</p>    1 -Alan     2 -Alan     3 -Alan

为什么我似乎无法在 #each 块中使用 json 数据的其他部分?有办法吗?

我是车把方面的新手,所以我不确定我需要搜索什么术语。事实证明,我能够找到答案,并想留下我的问题,以防其他人遇到同样的问题。事实证明,在我的示例中,您不能仅使用 {{firstName}} 并按预期获得 Alan 的原因是您处于 json 数据中 "list" 的上下文中。要返回到 json 数据的根目录,您需要使用如下语法:

var ui  = "<p>{{lastName}}, {{firstName}}</p>";
ui  = ui + "{{#each list}}";
ui  = ui + "    {{this}} - {{ ../firstName }}";
ui  = ui + "{{/each}}";

您可以在上面看到,在请求 firstName 值之前,我正在使用 {{ ../firstName }} 上一级到根。这对我有用,我希望它可以帮助其他人。

因为当您使用 {{#each}} 时,您处于子上下文中,即 list,现在您想要访问 firstName,它位于父上下文中,你可以使用 {{../firstName}} 访问它,就像这样。

{{#each list}}
    {{this}} - {{../firstName}}
{{/each}}

来自documentation,

Nested each blocks may access the iteration variables via depth based paths. To access the parent index, for example, {{@../index}} can be used.