Skip to content

Instantly share code, notes, and snippets.

@RobinThrift
Created April 10, 2014 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobinThrift/10375204 to your computer and use it in GitHub Desktop.
Save RobinThrift/10375204 to your computer and use it in GitHub Desktop.
A Handlebar.js helper that returns a given number of items in an array starting from a given index
Handlebars.registerHelper('limit', function(collection, limit, start) {
var out = [],
i, c;
start = start || 0;
for (i = c = 0; i < collection.length; i++) {
if (i >= start && c < limit+1) {
out.push(collection[i]);
c++;
}
}
return out;
});
@mansona
Copy link

mansona commented Jul 17, 2014

Eh... is there any reason why you didn't just do this:

Handlebars.registerHelper('limit', function(collection, limit, start) {
    return collection.slice(start, start + limit);
});

Also there is a bug in current implementation, line 8: If you are starting count (c) from 0 you don't need to have c < limit + 1 : remove the +1

@expalmer
Copy link

In this case I think that we need to do this.

Handlebars.registerHelper('limit', function( collection, limit, start ) {
  return collection.slice( start, limit + 1 );
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment