问题
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 first two match.
See the example code, there should be three variations under each combination of two, but if the first two match like red/red, then it just skips that {{#../../colors as |color3|}} part.
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var context = {colors: ['red','blue', 'green']};
var html = template(context);
document.getElementById("output").innerHTML = html;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<script id="entry-template" type="text/x-handlebars-template">
output:
{{#colors as |color1|}}
{{#../colors as |color2|}}
{{color1}} / {{color2}};
{{#../../colors as |color3|}}
{{color1}} / {{color2}} / {{color3}};
{{/../../colors}}
{{/../colors}}
{{/colors}}
</script>
<pre id="output">
</pre>
https://codepen.io/samkeddy/pen/BmNYrZ
回答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}}
来源:https://stackoverflow.com/questions/47041164/handlebars-prints-wrong-thing-when-iterating-through-same-array-thrice