[英]Meteor pass a dynamic variable from template to helper
我正在做一个流星项目,我想根据对象的属性将同一集合中的对象放置在不同的div中。 解释的最简单方法可能是显示一个测试用例:
<template name="board">
{{#each rows}}
<div id="row-{{this}}" class="row">
{{#each columns}}
<div id="{{..}}-{{this}}" class="column column-{{this}} row-{{..}}- column">
{{>pins }}
</div>
{{/each}}
</div>
{{/each}}
</template>
<template name="pins">
{{#each pins}}
<div class = "pin" >{{this}}</div>
{{/each}}
</template>
Template.board.helpers({
rows: [
'top',
'middle',
'bottom'
],
columns: [
'left',
'center',
'right'
]
});
Template.pins.helpers({
pins:[
{name: 'test1', loaction: 'bottomcenter'},
{name: 'test2', loaction: 'topleft'},
{name: 'test3', loaction: 'bottommcenter'},
{name: 'test4', loaction: 'middleright'}
]
});
我想根据引脚的位置将其放置在正确的div中。 现在,我当然可以手动写出html中的每个div以及每个div的帮助器(如果没有更好的解决方案,它将提供帮助),但是我试图找出最有效的解决方案是什么。
我尝试使用以下代码将位置传递回辅助函数:
{{#each pins location="{{..}}{{this}}}}
和这个
{{#each pins location="{{..}}{{this}}"}}
并运行一个函数,但是location =之后的标记以{{..}}{{this}}
而不是通过值来出现。
我还尝试过重组数据,如下所示:
pins:{
bottomcenter: [{name: 'test1'}, {name: 'test3'}]
topleft:[{name: 'test2'}]
}
等等,并将参数作为数据上下文传递:
{{>pins {{..}}{{this}}}}
但这似乎也不起作用。 任何帮助表示赞赏!
您的模板应为:
<template name="pins">
{{#each pins}}
<div class = "pin" >{{this.name}} {{this.location}}</div>
{{/each}}
</template>
和这样的助手:
Template.pins.helpers({
pins: function() {
return [
{name: 'test1', loaction: 'bottomcenter'},
{name: 'test2', loaction: 'topleft'},
{name: 'test3', loaction: 'bottommcenter'},
{name: 'test4', loaction: 'middleright'}
]
}
});
我想我明白了! 诀窍似乎是您不能将{{}}
括号嵌入其他{{}}
括号中。 因此,您使用:
<template name="pins">
{{#each pins .. this}}
<div class="pin">
{{this.name}}
</div>
{{/each}}
</template>
..
并将this
传递回helper函数,然后您可以根据结果进行搜索:
Template.pins.helpers({
pins: function(row,col){
var search = row+"-"+col;
var results = [];
var pinarr = [
{insert data here}
];
for(var i = 0; i < pinarr.length ; i++){
if(pinarr[i].location === search) {
results.push(pinarr[i]);
}
}
return results;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.