meteorhandlebars.jsmeteor-blaze

Meteor & Handlebars: new row after every N-items


I have this markup:

<div class="row">
  {{#each items}}
    <div class="col-md-4>{{ItemHere}}</div>
  {{/each}}
</div>

I need to group every 3 elements in row, for example:

<div class="row">
  <div class="col-md-4>Item1</div>
  <div class="col-md-4>Item2</div>
  <div class="col-md-4>Item3</div>
</row>
<div class="row">
  <div class="col-md-4>Item4</div>
  <div class="col-md-4>Item5</div>
  <div class="col-md-4>Item6</div>
</row>
...

How can I achieve this with Blaze? Are there any built-in functions or helpers?


Solution

  • I'd create a helper to separate your data into arrays of arrays:

    // Helper:
    Template.templateName.helpers({
      getItemsInGroupsOfThree( array ) {
        var result = [];
        var currentResultIndex = 0;
        for( var i = 0; i < array.length; i++ ) {
          if( i % 3 === 0 ) {
            if( i !== 0 ) currentResultIndex++;
            result.push({ items: [ array[i] ] });
          } else {
            result[ currentResultIndex ].items.push( array[i] );
          }
        }
        return result;
      }
    });
    
    //Template:
    {{#each itemGroup in getItemsInGroupsOfThree items}}
      <div class="row">
        {{#each item in itemGroup.items}}
          <div class="col-md-4>
            {{ItemHere}}
          </div>
        {{/each}}
      </div>
    {{/each}}
    

    The helper creates an array of arrays with up to three of your items in each array. You're basically using the created groups to add each row, and then the items within the groups create the columns and output values.

    Hope this helps!