Skip to content Skip to sidebar Skip to footer

Handlebars Prints Wrong Thing When Iterating Through Same Array Thrice

I thought I had this resolved in my last post, switching to using as |var| worked for loops inside loops. But now if I throw a third one inside, it wont do the third loop if the fi

Solution 1:

I investigated this issue and provided an explanation of its cause, which you can read at https://stackoverflow.com/a/40955937/3397771.

The gist of the issue is that Handlebars does not add a context object to the stack when the new context object is equal to the one currently at the top of the stack. Equality in this case is just a simple JavaScript comparison, which, for primitives like Strings and Numbers, is a value comparison. In your case, this means that the path to the root context is different when the inner and outer loops have the same value ('red'/'red') than it is when they have different values ('red'/'blue').

The way I would solve your issue is to use the Handlebars @root variable in order to avoid using the relative path to your root context. Your template would look like the following:

{{#@root.colors as |color1|}}
    {{#@root.colors as |color2|}}
        {{color1}} / {{color2}};
        {{#@root.colors as |color3|}}
            {{color1}} / {{color2}} / {{color3}};
        {{/@root.colors}}
    {{/@root.colors}}  
{{/@root.colors}}

Or alternatively:

{{#each @root.colors as |color1|}}
    {{#each @root.colors as |color2|}}
        {{color1}} / {{color2}};
        {{#each @root.colors as |color3|}}
            {{color1}} / {{color2}} / {{color3}};
        {{/each}}
    {{/each}}  
{{/each}}

Post a Comment for "Handlebars Prints Wrong Thing When Iterating Through Same Array Thrice"