Reputation: 436
I have handlebars based email template for mandrill and am trying to render JSON data from a list of lists where each list can have up to 3 items. For each inner list handlebars iterates over, it is supposed to check if there is anything at index 0,1,2 and if so do something with them, like this:
{{#each thing}}
{{#if this.thing.[0]}}
Do something here
{{/if}}
{{#if this.thing.[1]}}
Do something here
{{/if}}
{{#if this.thing.[2]}}
Do something here
{{/if}}
{{/each}}
I have noticed that when the list being iterated over only has 2 items, handlebars will take the 3rd item from the last list that had 3 items, so I guess this.[2] isn't block scoped?
For instance if I use:
thing = [
["a","b","c"],
["d","e"]
]
I get:
Something with "a"
Something with "b"
Something with "c"
Something with "d"
Something with "e"
Something with "c"
I'm not sure if this is an issue with mandrills implementation of handlebars of handlebars itself, as I'm new to both.
Any help would be much appreciated
Upvotes: 1
Views: 410
Reputation: 31
Currently it seems like Mandrill changes the context in the #each block a bit funny. This is not from Handlebars, but rather - Mandril's implementation of it (and I hope they fix it). If there are 2 objects being iterated over, and the first one has a property, but not the second (in your case -> this.thing.[2]) - when the second one comes into scope, the property does not get 'cleared'. What you could do is assign it to 'false' explicitly -
thing = [
["a","b","c"],
["d","e", false]
];
Might be easier if you use objects instead of arrays, this.[2] looks less readable than this.c ( I am assuming you meant this.[2] instead of this.thing[2] ). E.g. using
thing = [
{ a : true, b : true, c : true },
{ d : true, e : true, c : false}
]
with the same template should work just fine. {{@key}} gives you access to the keys.
Upvotes: 3
Reputation: 2200
To my mind you should iterate 2 times with #each and not use #if
Here is an example
<script id="entry-template" type="text/x-handlebars-template">
{{#each thing}}
{{#each item}}
{{value}}
{{/each}}
{{/each}}
</script>
https://jsfiddle.net/ChristopheThiry/y1nmx738/
Upvotes: 0