Search code examples
javascriptmeteoreachmeteor-blaze

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 :

  • {{@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.


Solution

  • 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}}