简体   繁体   English

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

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

I have block of json data that contains an array (example) 我有包含数组的json数据块(示例)

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

I want to use the #each syntax to loop over the items in the array and create a string for each item that contains both the item in the array as well as another piece of my incoming json data. 我想使用#each语法循环遍历数组中的项目,并为包含数组中的项目以及传入的json数据的另一项的每个项目创建一个字符串。 This is what I am trying: 这是我正在尝试的:

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));

but it is not outputting what I am expecting. 但它没有输出我所期望的。 I get this (wrong): 我得到这个(错误):

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

but I WANT to see this: 但我想看看:

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

why is it that I cant seem to use other parts of my json data within the #each block? 为什么我似乎无法在#each块中使用json数据的其他部分? Is there a way to do this? 有没有办法做到这一点?

Since when you're using {{#each}} , you're in a child context, which is list , now you want to access firstName , which is in parent context, you can use {{../firstName}} to access it, like this. 由于使用{{#each}} ,您处于子上下文list ,现在您要访问父上下文中的firstName ,因此可以使用{{../firstName}}来像这样访问它。

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

From the documentation , 文档中

Nested each blocks may access the iteration variables via depth based paths. 嵌套的每个块可以通过基于深度的路径访问迭代变量。 To access the parent index, for example, {{@../index}} can be used. 要访问父索引,例如,可以使用{{@ .. / index}}。

I am new at handlebars so I wasnt sure what term I needed to be searching for. 我是车把的新手,所以我不确定要搜索什么术语。 As it turns out I was able to find the answer and wanted to leave my question up in case someone else had the same issue. 事实证明,我能够找到答案,并想把我的问题保留下来,以防其他人遇到相同的问题。 As it turns out the reason you cant just use the {{firstName}} and get the Alan as expected in my example is that you are in the context of the "list" in the json data. 事实证明,您不能仅使用{{firstName}}并按我的示例中的预期获得Alan的原因是,您处于json数据中“列表”的上下文中。 To get back up to the root of the json data you need to use the syntax like this: 要恢复到json数据的根,您需要使用如下语法:

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

You can see above that I am using {{ ../firstName }} to come up one level to the root before requesting the firstName value. 您可以在上方看到我在请求firstName值之前使用{{../firstName}}到根目录下一级。 This worked for me and I hope it can help someone else. 这对我有用,我希望它可以帮助其他人。

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

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