HOW TO: Loop through arrays using #each handlebar
This covers two scenarios on looping through arrays using the #each handlebar.
SCENARIO 1:
You have a loop in an EDI file, such as N1, that contains several values. For this example, we'll say that they are addresses, each of which has a value - BY, BT, and ST. You want to ensure that the addresses are ordered properly. You've put the numeric loop in the template, but want to set the address value based on the Entity Identifier Code instead of a fixed numeric value.
To handle this, you'll need to do is loop through the N1 array, then use a handlebars compare statement to check if the "Entity Code Identifier" matches what you need. Here is an example:
Using this as sample data:
{
"myData":
{
"N1": [
{
"Entity Identifier Code": "BY",
"Name": "Example1 - BY",
"Identifier Code Qualifier": "92",
"Identification Code": 123
},
{
"Entity Identifier Code": "BT",
"Name": "Example2 - BT",
"Identifier Code Qualifier": "92",
"Identification Code": 456
},
{
"Entity Identifier Code": "ST",
"Name": "Example3 - ST",
"Identifier Code Qualifier": "92",
"Identification Code": 789
}]
}
}
You can use the following expression to extract each block after looping through the N1 array:
{{#each myData.N1}}
{{#compare this.[Entity Identifier Code] "==" "BY"}}
(BY SEGMENT GOES HERE)
{{this.Name}}
{{else}}{{#compare this.[Entity Identifier Code] "==" "BT"}}
(BT SEGMENT GOES HERE)
{{this.Name}}
{{else}}{{#compare this.[Entity Identifier Code] "==" "ST"}}
(ST SEGMENT GOES HERE)
{{this.Name}}
{{else}}
(DEFINE CASE IF NO MATCH FOUND, leaving empty string is fine as well){{/compare}}{{/compare}}{{/compare}}
{{/each}}
Note that whitespace and newlines will also be evaluated in the template, so you can remove those if needed once you've written your desired expression. This should allow you pick out the fields and place them in the desired segment without the need of hard coding the index of the N1 array.
SCENARIO 2:
Your EDI file has a loop that defines the parts and quantities that have been ordered. You need a dynamic way to loop through these values to build the JSON.
To handle this, you'll have to do something similar to what was done here, except construct a new array after looping through the initial array. Here is an example:
[{{#each item}}
{"newProperty": "{{this.itemname}}"}{{#unless @last}},{{else}}{{/unless}}
{{/each}}
]
This expression should allow you to dynamically generate an array from looping through the initial array.
Comments
Please sign in to leave a comment.