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

2

5

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.

Redstart answered 27/3, 2015 at 18:16 Comment(0)
B
7

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

});
Barilla answered 27/3, 2015 at 18:49 Comment(2)
Awesome! This works great. I added a number to the object array and used it inside the block to display the numbering I wanted: meteorpad.com/pad/rbyBzy4FzBtZauK8m/Repeat%20template%20blockRedstart
Just realized as I submitted that comment that I could probably just put them in an ordered list instead.Redstart
T
0

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}}
Transonic answered 25/6, 2016 at 22:46 Comment(2)
Would be great to have this example written also in plain JSMechelle
ES6: loop: (count) => new Array(count).fill({})Hejira

© 2022 - 2024 — McMap. All rights reserved.