How can I repeat a block N times in a Meteor Spacebars template?

我是研究僧i 提交于 2019-12-06 03:40:20

问题


I have this block of code in a Spacebars template:

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

I would like to repeat this N times incrementing the number each time like so:

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>

I would love to be able to pass N to a custom template tag to take care of this (e.g. {{choices 3}}). What's a nice DRY way to do this? I have a vague notion I could write a template helper, but I'm not sure where to start.


回答1:


Working Example: http://meteorpad.com/pad/THAQfpfrru5MgAGnS/Copy%20of%20Leaderboard

You can pass a count in and return an array of arbitrary objects. Not the most elegant... but it worked!

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:


If you're using the underscore package for Meteor, and also happen to be using CoffeScript, you can create the following single-line template helper:

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

You can then use this helper in your template:

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


来源:https://stackoverflow.com/questions/29307531/how-can-i-repeat-a-block-n-times-in-a-meteor-spacebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!