在两次迭代相同阵列时,把手会打印错误的东西
问题描述:
试图从数组中打印2个项目的所有组合。在两次迭代相同阵列时,把手会打印错误的东西
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>
这里是一个Codepen Demo
答
我还不知道是什么导致它的行为是那样,但你可以通过使用块参数修复它。
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>
+0
这解决了这个问题,但现在我在添加第三个循环时出现类似问题https: //*.com/questions/47041164/handlebars-prints-wrong-thing-when-iterating-through-same-array-thrice – stackers
的可能的复制[../this返回内环当父和子具有相同的值的内部视图对象(https://*.com/questions/40935524/ this-returns-the-view-object-inside-inner-loop-when-the-the-and-child-have) – 76484