【问题标题】:How can I repeat a block N times in a Meteor Spacebars template?如何在 Meteor Spacebars 模板中重复 N 次块?
【发布时间】:2015-06-01 04:26:56
【问题描述】:

我在空格键模板中有这段代码:

1.
<select class="form-group">
  {{#each choices}}
    <option>{{this}}</option> 
  {{/each}}
</select>

我想重复此 N 次,每次递增数字,如下所示:

1.
<select class="form-group">
  {{#each choices}}
    <option>{{this}}</option> 
  {{/each}}
</select>
2.
<select class="form-group">
  {{#each choices}}
    <option>{{this}}</option> 
  {{/each}}
</select>
3.
<select class="form-group">
  {{#each choices}}
    <option>{{this}}</option> 
  {{/each}}
</select>

我希望能够将 N 传递给自定义模板标签来处理这个问题(例如 {{choices 3}})。有什么好的 DRY 方法可以做到这一点?我有一个模糊的想法,我可以编写一个模板助手,但我不知道从哪里开始。

【问题讨论】:

    标签: meteor meteor-blaze spacebars


    【解决方案1】:

    工作示例: http://meteorpad.com/pad/THAQfpfrru5MgAGnS/Copy%20of%20Leaderboard

    您可以传入一个计数并返回一个任意对象的数组。不是最优雅的......但它确实有效!

    HTML

    <body>
      {{>content}}
    </body>
    
    <template name="content">
        {{#each loopCount 5}}
          <select class="form-group">
            {{#each choices}}
              <option>{{this}}</option> 
            {{/each}}
          </select>
        {{/each}}
    </template>
    

    JS

    Template.content.helpers({
    
      choices: function(){
        return ['choice1','choice2','choice3']
      },
    
      loopCount: function(count){
        var countArr = [];
        for (var i=0; i<count; i++){
          countArr.push({});
        }
        return countArr;
      }
    
    });
    

    【讨论】:

    【解决方案2】:

    如果您正在使用 Meteor 的下划线包,并且恰好使用 CoffeScript,您可以创建以下单行模板帮助程序:

    t.helpers
      loop: (count) -> {} for i in _.range count
    

    然后你可以在你的模板中使用这个助手:

    {{! Will display 'Output' 5 times }}
    {{#each loop 5}}
        Output 
    {{/each}}
    

    【讨论】:

    • 如果这个例子也用纯 JS 编写会很棒
    • ES6: loop: (count) =&gt; new Array(count).fill({})