Every Nth Item in Handlebars

You’re all jazzed and using your favourite CSS grid but you’ve run into a wall in your Handlebars template. You’ve got a template that outputs a list of books. The problem is after every third book you need to start a new row. You’re stuck. Well… look no further I’ve got just the helper for you, grouped_each. It’s part helper, part convention. Stronger than mere mortal men.

Here’s how it works. It has two parameters. The first is the number items in each group and the second is an array of items. That’s the helper part. Now here’s the convention. Inside the grouped_each block you use the built-in each helper to iterate over this. For example look at the following Handlebars template.

<div class="container">
{{#grouped_each 3 books}}
<div class="row">
{{#each this }}
<div class="span4 book" data-isbn="{{ isbn }}">
<strong>{{ name }}</strong>
</div>
{{/each}}
</div>
{{/grouped_each}}
</div>
view raw 412.handlebars hosted with ❤ by GitHub

And finally here’s the magic sauce that is the helper.

Handlebars.registerHelper('grouped_each', function(every, context, options) {
var out = "", subcontext = [], i;
if (context && context.length > 0) {
for (i = 0; i < context.length; i++) {
if (i > 0 && i % every === 0) {
out += options.fn(subcontext);
subcontext = [];
}
subcontext.push(context[i]);
}
out += options.fn(subcontext);
}
return out;
});
view raw 412.js hosted with ❤ by GitHub