stackers
stackers

Reputation: 3280

Handlebars prints wrong thing when iterating through same array twice

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

Upvotes: 0

Views: 286

Answers (1)

castletheperson
castletheperson

Reputation: 33496

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>

Upvotes: 1

Related Questions