流星将动态变量从模板传递给助手

Meteor pass a dynamic variable from template to helper

我正在做一个流星项目,我想根据它们的属性将同一集合中的对象放在不同的 div 中。最简单的解释方法可能是展示一个测试用例:

html

<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>

js

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 并为每个人写一个助手(如果没有更好的解决方案,我会这样做),但我试图找出最有效的解决方案是。

我尝试使用以下代码将位置传回辅助函数:

 {{#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 传回辅助函数,然后您可以根据结果进行搜索:

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;
  }

 });
}