简体   繁体   中英

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

I have block of json data that contains an array (example)

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. 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? 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}}
    {{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.

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. To get back up to the root of the json data you need to use the syntax like this:

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. This worked for me and I hope it can help someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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