Last active
January 23, 2017 15:19
-
-
Save hu9o/7e915b526571ac1adea08a322d848638 to your computer and use it in GitHub Desktop.
Handlebars helper: #each-paginate
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
var Handlebars = require('handlebars'); | |
// with `ctx` = [a, b, c, d, e, f, g, h] and `count` = 3 | |
// will iterate over [[a, b, c], [d, e, f], [g, h]] | |
Handlebars.registerHelper('each-paginate', function(context, opts) { | |
// similar to Python's range | |
var range = n => Array.from(new Array(n).keys()); | |
// items per page and page count - defaults to a single page with all the items | |
var perPage = opts.hash.perPage || context.length; | |
var pageCount = Math.ceil(context.length / perPage); | |
// array of arrays | |
var pages = range(pageCount).map(i => context.slice(i*perPage, (i+1)*perPage)); | |
return Handlebars.helpers.each(pages, opts); | |
}); | |
/* | |
Example : | |
{{#each-paginate products perPage=4}} | |
<div class="row"> | |
{{#each this}} | |
<article class="product"> | |
<h4 class="product-title">{{name}}</h4> | |
<p class="benefits turquoise">{{info}}</p> | |
<p class="benefits-description">{{desc}}</p> | |
</article> | |
{{/each}} | |
</div> | |
{{/each-paginate}} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment