Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 649
raddevon Avatar asked Mar 27 '15 18:03

raddevon


1 Answers

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

});
like image 113
neal Avatar answered Nov 15 '22 11:11

neal