Reputation: 5148
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.
Upvotes: 1
Views: 1856
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
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