SalahAdDin SalahAdDin - 7 months ago 7
HTML Question

Break up an {{# each}} block every N items

I'm working in a meteor project that needs to display a grid of users as shown here:

grid Layout

In Django was easy, I would use the list counter and get its modulo, and if the module was 0, then I would close the

row div
tag and add a new
row div
tag.

{% if forloop.counter|divisibleby:'2' %}
</div>
<div class="row">
{% endif %}


But when I try to do this in a Meteor template:

Template.available_user_list.helpers({
users: function () {
return Meteor.users.find();
},
count: ()=>{
return Meteor.users.find().count();
},
isModulo: function (dividend, divisor) {
return dividend % divisor == 0;
}
});


html

<!-- display a list of users -->
<template name="available_user_list">
<h2>Choose someone to chat with:</h2>
<div class="row">
{{#each users}}
{{> available_user}}
{{#if isModulo count 4 }}
</div>
<div class="row">
{{/if}}
{{/each}}
</div>
</template>


I get the following error:


=> Errors prevented startup:

While processing files with templating (for target web.browser):
client/templates/lobby_page.html:14: Unexpected HTML close tag
... if isModule tags.


I can't use the pattern as Django. How can I insert a new row every N items?

Answer

I'm not really familiar with Meteor, but the pattern I would use is to split the array into "chunks" of the size you want, then loop over each chunk for the divs, then loop over each chunks users:

Template.available_user_list.helpers({
  users: function () {
    return Meteor.users.find();
  },
  count: ()=>{
    return Meteor.users.find().count();
  },
  chunks: function(chunkSize) {
      var R = [];
      var users = Meteor.users.find();
      for (var i=0,len=users.count(); i<len; i+=chunkSize)
          R.push(users.slice(i,i+chunkSize));
          return R;
  }
});

<!-- display a list of users -->
<template name="available_user_list">
  <h2>Choose someone to chat with:</h2>
  {{#each chunk 4}}
      <div class="row">
          {{#each .}}
              {{> available_user}}
          {{/each}}
      </div>
  {{/each}}
</template>
Comments