【问题标题】:Meteor pass a dynamic variable from template to helperMeteor 将动态变量从模板传递给助手
【发布时间】:2015-09-30 06:46:13
【问题描述】:

我正在做一个流星项目,我想根据它们的属性将来自同一集合的对象放置在不同的 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 并为每个 div 写出一个助手(如果没有更好的解决方案,我会这样做),但我正在尝试找出最有效的解决方案。

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

 {{#each pins location="{{..}}{{this}}}}

还有这个

 {{#each pins location="{{..}}{{this}}"}}

并运行一个函数,但 location= 之后的标签以 {{..}}{{this}} 的形式出现,而不是值。

我也尝试过这样重构数据:

 pins:{
  bottomcenter: [{name: 'test1'}, {name: 'test3'}]
  topleft:[{name: 'test2'}]
 }

等,并将参数作为数据上下文传递:

{{>pins {{..}}{{this}}}}

但这似乎也不起作用。任何帮助表示赞赏!

【问题讨论】:

    标签: javascript meteor handlebars.js


    【解决方案1】:

    我想我明白了!诀窍似乎是您不能将 {{}} 括号嵌入到其他 {{}} 括号中。所以你使用:

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

    【讨论】:

      【解决方案2】:

      你的模板应该是这样的:

      <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'}
            ]
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2016-01-07
        • 2015-07-10
        • 2015-09-02
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 2016-06-10
        • 2015-03-28
        相关资源
        最近更新 更多