Arthur
Arthur

Reputation: 5148

Multiple each index on Meteor Blaze

I'm using Blaze from Meteor for html template, and I have multiple loop like :

let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
let attrs = ['name', 'age']


{{#each objects}}
  <h3>Object {{@index}}</h3>
  {{#each attrs}}
    [...] // code here
  {{/each}}
{{/each}}

I know :

Now, I want on [...] the current index for the objects loop. I search a lots on Google and Stackoverflow but didn't found.

Upvotes: 1

Views: 1856

Answers (2)

Arthur
Arthur

Reputation: 5148

Huumm, News about Blaze allow new to create variable (with #let). An easy solution is:

let objects = [{name: 'John', age: 18}, {name: 'Foo', age: 25}, {name: 'Bar', age: 35}]
let attrs = ['name', 'age']


{{#each objects}}
  {{#let object=this object_idx=@index}}
    <h3>Object {{object_idx}}</h3>

    {{#each attrs}}
      Object idx {{object_idx}} | Object {{object}}
      Attr idx {{@index}} | Attr {{this}}
    {{/each}}

  {{/let}}
{{/each}} 

Updated: You can even do {{#each object in objects}} since a while, avoid you to do {{#let object=this}}

{{#each object in objects}}
  {{#let object_idx=@index}}
    <h3>Object {{object_idx}}</h3>

    {{#each attr in attrs}}
      Object idx {{object_idx}} | Object {{object}}
      Attr idx {{@index}} | Attr {{attr}}
    {{/each}}

  {{/let}}
{{/each}} 

Upvotes: 4

Michel Floyd
Michel Floyd

Reputation: 20227

You'll need to create a helper for the inner loop as follows:

Template.myTemplate.helpers({
  value: function(){
    return Template.parentData(1)[this];
  }
});

Template.parentData(1) returns the data context one (1) level up from the current level. [this] references the key of that object given by the current data.

Upvotes: 2

Related Questions