How can I use other template values inside a handlebar each helper?
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?
2 Answers
2
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.
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.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
yeah I didnt see your answer and also answered below (after figuring it out), thanks for the quick and clear answer. I marked it.
– contractorwolf
Sep 12 '18 at 0:35