Handlebars prints wrong thing when iterating through same array twice

假如想象 提交于 2019-12-25 11:55:32

问题


Trying to print out all combinations of 2 items from an array.

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}}
        {{#../colors}}
    color1: {{../this}} color2: {{this}};
        {{/../colors}}
    {{/colors}}
</script>
<pre id="output">
  </pre>

Here is a Codepen Demo


回答1:


I'm not yet sure what's causing it to behave that way, but you can fix it by using block parameters.

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: {{color1}} color2: {{color2}};
        {{/../colors}}
    {{/colors}}
</script>
<pre id="output">
  </pre>


来源:https://stackoverflow.com/questions/46996314/handlebars-prints-wrong-thing-when-iterating-through-same-array-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!