L. L. Blumire
L. L. Blumire

Reputation: 355

Nested top level each in handlebars

Given this context

{
  letters: ['a', 'b', 'c'],
  numbers: ['1', '2', '3']
}

How would I produce

a1
a2
a3
b1
b2
b3
c1
c2
c3

In essence,

{{#each letters}}
{{#each ../numbers}}
what to put here?
{{/each}}
{{/each}}

I am specifically using https://github.com/sunng87/handlebars-rust, however this in theory has very close to feature parity, so how it would be done in handlebars.js should be compatible.

For reference, my actual usecase is C++ code generation. And the question is largely about accessing this this propery of an internal loop. Right now my code looks like

{{#each variant}}
{{#each ../typearg}}{{#if @first}}template <{{/if}}{{this}}{{#if @last}}>{{else}},{{/if}}{{/each}}
{{/each}}

However for some reason, this outputs

template <>
template <>

when I am expecting it to output

template <T>
template <T>

The object as is relevant and being passed to it is in the form

{
    typearg: [ 'T' ],
    variant: [{ }, { }]
}

Upvotes: 1

Views: 1128

Answers (1)

Sushanth --
Sushanth --

Reputation: 55750

I think the best way out would be is to create a new handlebar helper which would return you the html.

Handlebars.registerHelper('multi_list', function(context, options) {
  var html = "";
  var letters = options.hash.letters;
  var numbers = options.hash.numbers;

  for (var i=0; i< letters.length; i++) {
    for (var j=0; j <  numbers.length; j++) {
        html += '<li>' + (letters[i] + '' + numbers[i] + '</li>';
    }
  }

  return html;
});

And you would call the helper

{{#multi_list letters numbers}}

If you want to still iterate using the existing each helper, then you can use {{this}} or {{./this}} to access the innermost loop value and

{{../this}} to access the outermost loop value which is one level higher

{{#each variant}}
    {{#each ../typearg}}
        {{#if @first}}
            template <
        {{/if}}
            {{this}}
         {{#if @last}}
            >
         {{else}}
            ,
         {{/if}}
     {{/each}}

      {{../this}}

 {{/each}}

Upvotes: 1

Related Questions