dec
dec

Reputation: 604

Meteor, Blaze: create a simple loop with each?

A simple problem, but I can`t find the simple solution. Did I have to write a helper for that?

I want to create a specific amount of li items in a template. The concrete number is given through a parameter called max.

{{> rating max=10 value=rating }}

<template name="rating">
    <ul class="rating">
        {{#each ?}}
            <li  class="star">\u2605</li>
        {{/each }}
    </ul>
</template>

Upvotes: 2

Views: 2600

Answers (3)

Kani
Kani

Reputation: 840

Im fine with:

Template.registerHelper('repeat', function(max) {
    return _.range(max); // undescore.js but every range impl would work
});

and

{#each (repeat 10)}}
    <span>{{this}}</span>
{{/each}}

Upvotes: 4

Michel Floyd
Michel Floyd

Reputation: 20227

Simply return the required number of items from the underlying helper:

html:

{{> rating max=10 value=rating }}

<template name="rating">
    <ul class="rating">
        {{#each myThings max}}
            <li class="star">\u2605</li>
        {{/each }}
    </ul>
</template>

Note that max needs to be passed through the html template to the {{#each}}

js:

Template.rating.helpers({
  myThings: function(max){
    // return an array 0...max-1 (as convenient as any other set of values for this example)
    return Array.apply(null, Array(max)).map(function (x, i) { return i; });
  }
});

Of course if you were iterating over a collection then you could just limit your .find() to max.

I also notice your rating template isn't using the parameter value anywhere. Did you mean to do:

<ul class = "{{value}}">

or was the value supposed to be substituted elsewhere?

Upvotes: 0

perusopersonale
perusopersonale

Reputation: 896

From http://docs.meteor.com/#/full/blaze_each:

Constructs a View that renders contentFunc for each item in a sequence.

So each must be used with a sequence (array,cursor), so you have to create a helper that create a sequence to use #each. Usually view is customized by item value, but in your case an array with max size will do the job.

Or you can create a custom template helper where you can pass html to repeat and number of repetition and concat html in helper. Something like(code not tested):

// Register helper
htmlRepeater = function (html,n) {
   var out = '';
   for(var i=0 ; i<n;i++) 
       out.contat(html);
   return  Spacebars.SafeString(out);
};

Template.registerHelper('repeat', htmlRepeater);
------------------------
// in template.html
{{{repeat  '<li  class="star">\u2605</li>' max}}}

Upvotes: 2

Related Questions