Reputation: 1439
I have these nested iterators:
<ul class='detailViewList'>
{{#each detailsCollection}}
<li id={{_id}} class='detailViewEntry {{checkboxStatus}}'>
<input type="checkbox" class='detailCheckbox'>
<b>{{detail}}</b>
<div class="btn btn-xs btn-danger" id="delete-detail">x</div>
<form class='form-inline'>
<div class="form-group">
<input type="text" id='{{_id}}' name='message' class="form-control" placeholder="message">
</div>
</form>
{{#each messagesCollection}}
{{#if isMessageForThisDetail}}
{{message.message}}
{{/if}}
{{/each}}
</li>
{{/each}}
</ul>
And I understand that I can access parent attributes from child template via handlebars path, from docs:
{{./name}} or {{this/name}} or {{this.name}}
But I need my helper isMessageForThisDetail
to compare an attribute of the currently iterated messageCollection
to the currently iterated parent detailsCollection
. My helper for that looks like this:
isMessageForThisDetail: function(){
var message = messagesCollection.findOne({detailId: this._id});
if(message != undefined){
return this._id == message._id;
} else {
console.log('there is no message for this detail');
}
}
But the context of this._id
is the message, not the _id
of the detail I want to compare a field of the message to.
Upvotes: 3
Views: 1965
Reputation: 731
(not verified)
Option 1:
Template
{{#each companies}}
{{#each employee this}}
<a href="">{{this}}</a>
{{/each}}
{{/each}}
Helper
var templateHelpers = {
companies: function () {
// array of companies
return arrayOfCompanies;
},
employee: function (company) {
var companyId = company.id;
// do something with companyId
}
}
Option 2:
Template
{{#each companies}}
{{#each employee this.id}}
<a href="">{{this}}</a>
{{/each}}
{{/each}}
Helper
var templateHelpers = {
companies: function () {
// array of companies
return arrayOfCompanies;
},
employee: function (companyId) {
// do something with companyId
}
}
Upvotes: 1
Reputation: 1061
I was stuck in a similar way and found that the Template.parentData() approach currently doesn't work within event handlers (see https://github.com/meteor/meteor/issues/5491). User Lirbank posted this simple workaround:
Pass the data from the outer context to an html element in the inner context, in the same template:
{{#each companies}}
{{#each employees}}
<a href="" companyId="{{../id}}">Do something</a>
{{/each}}
{{/each}}
Now the company ID can be accessed from the event handler with something like
$(event.currentTarget).attr('companyId')
Upvotes: 6
Reputation: 64312
You should be able to access the parent data like so:
isMessageForThisDetail: function() {
var detailId = Template.parentData(1)._id;
var message = messagesCollection.findOne({detailId: detailId});
if(message)
return this._id === message._id;
else
console.log('there is no message for this detail');
}
Upvotes: 8