我遇到了模板上下文的情况,我很难找到解决方法.
这是有问题的模板:
{{#each votes}}
<h3>{{question}}</h3>
<ul>
{{#each participants}}
<li>
<p>{{email}}</p>
<select name="option-select">
{{#each ../options}}
<option value="{{option}}" class="{{is_selected_option}}">{{option}}</option>
{{/each}}
</select>
</li>
{{/each}}
</ul>
</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
这是一个投票文件的例子:
{
_id: '32093ufsdj90j234',
question: 'What is the best food of all time?'
options: [
'Pizza',
'Tacos',
'Salad',
'Thai'
],
participants: [
{
id: '2f537a74-3ce0-47b3-80fc-97a4189b2c15'
vote: 0
},
{
id: '8bffafa7-8736-4c4b-968e-82900b82c266'
vote: 1
}
]
}
Run Code Online (Sandbox Code Playgroud)
这就是问题......
当模板进入#each
for参与者时,它不再具有对vote
上下文的访问权限,因此无法访问每个投票的可用选项.
我可以稍微解决这个问题,通过使用../options
车把路径跳回到父上下文,但这并不影响模板辅助的情况下,所以this
在Template.vote.is_selected_option
指当前participant
,而不是当前的vote
或option
,并有没办法知道option
我们目前正在迭代哪些.
有关如何解决这个问题的任何建议,而不诉诸DOM操作和jQuery恶作剧?
对我来说,这是一个模板问题.我们需要一种在模板,模板助手和模板事件中达到模板上下文层次结构的正式方法.
opy*_*pyh 83
看来自Spacebars(Meteor的新模板引擎)以来,您可以访问{{#each}}
块内的父上下文../
.
在Meteor 0.9.1中,您还可以编写帮助程序并Template.parentData()
在其实现中使用.
它不是特别漂亮,但是我已经做了类似的事情:
<template name='forLoop'>
{{#each augmentedParticipants}}
{{> participant }}
{{/each}}
</template>
<template name='participant'>
...
Question: {{this.parent.question}}
...
</template>
// and in the js:
Template.forLoop.helpers({
augmentedParticipants: function() {
var self = this;
return _.map(self.participants,function(p) {
p.parent = self;
return p;
});
}
});
Run Code Online (Sandbox Code Playgroud)
它与AVGP建议的方法类似,但是在辅助程序级别而不是数据库级别增加了数据,我认为这是一个轻量级的方法。
如果您喜欢,可以尝试编写一个Handlebars块帮助eachWithParent
程序来抽象该功能。流星对车把的扩展记录在这里:https : //github.com/meteor/meteor/wiki/Handlebars
归档时间: |
|
查看次数: |
19973 次 |
最近记录: |