1

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 :

  • {{@index}} is used to know the current loop index (so on [..] {{@index}} is a ref to index on attrs array
  • {{this}} is used to know the current loop value (so on [...] {{value}} is name or age)
  • {{..}} is a ref to the parent loop value (so on [...] {{..}} is the current object, on first loop)

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

Arthur
  • 4,870
  • 3
  • 32
  • 57

2 Answers2

4

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}} 
Arthur
  • 4,870
  • 3
  • 32
  • 57
2

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.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
  • I want the index ! not the value – Arthur Jan 29 '16 at 17:25
  • 1
    Ah, sorry. I don't know that getting the index of the parent context is possible. I'd recommend that you *map* an index variable into your outer object array using @David Weldon's pattern from [this answer](http://stackoverflow.com/a/24226769/2805154) – Michel Floyd Jan 29 '16 at 17:46