How can I repeat a block N times in a Meteor Space

2020-07-13 07:36发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2020-07-13 08:04

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}}
查看更多
Viruses.
3楼-- · 2020-07-13 08:05

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

});
查看更多
登录 后发表回答