我有这些嵌套的迭代器:
<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>
我了解我可以通过docs的句柄路径从子模板访问父属性:
{{。/ name}}或{{this / name}}或{{this.name}}
但我需要帮助器isMessageForThisDetail
将当前迭代的messageCollection
的属性与当前迭代的父detailsCollection
进行比较。我的助手看起来像这样:
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');
}
}
但是this._id
的上下文是消息,而不是我想要将消息字段与之比较的详细信息的_id
。
答案 0 :(得分:8)
您应该可以像{...}那样访问parent data:
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');
}
答案 1 :(得分:6)
我遇到了类似的问题,发现Template.parentData()方法目前在事件处理程序中不起作用(参见https://github.com/meteor/meteor/issues/5491)。用户Lirbank发布了这个简单的解决方法:
将外部上下文中的数据传递到内部上下文中的html元素,在同一模板中:
{{#each companies}}
{{#each employees}}
<a href="" companyId="{{../id}}">Do something</a>
{{/each}}
{{/each}}
现在可以使用类似
的事件从事件处理程序访问公司ID $(event.currentTarget).attr('companyId')
答案 2 :(得分:1)
(未经核实)
选项1:
模板
{{#each companies}}
{{#each employee this}}
<a href="">{{this}}</a>
{{/each}}
{{/each}}
辅助
var templateHelpers = {
companies: function () {
// array of companies
return arrayOfCompanies;
},
employee: function (company) {
var companyId = company.id;
// do something with companyId
}
}
选项2:
模板
{{#each companies}}
{{#each employee this.id}}
<a href="">{{this}}</a>
{{/each}}
{{/each}}
辅助
var templateHelpers = {
companies: function () {
// array of companies
return arrayOfCompanies;
},
employee: function (companyId) {
// do something with companyId
}
}