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.
And finally here’s the magic sauce that is the helper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); |