Skip to content

Instantly share code, notes, and snippets.

@JerryC8080
Last active October 28, 2017 05:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JerryC8080/766152ad951887ae27c3 to your computer and use it in GitHub Desktop.
Save JerryC8080/766152ad951887ae27c3 to your computer and use it in GitHub Desktop.
paginate helper
var paginate = require('handlebars-paginate');
Handlebars.registerHelper('paginate', paginate);
/* ... */
var html = template({pagination: {
page: 3,
pageCount: 10
}});
<div class="pagination pagination-centered">
<ul>
{{#paginate pagination type="previous"}}
<li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}" >Prev</a></li>
{{/paginate}}
{{#paginate pagination type="middle" limit="7"}}
<li {{#if active}}class="active"{{/if}}><a href="?p={{n}}">{{n}}</a></li>
{{/paginate}}
{{#paginate pagination type="next"}}
<li {{#if disabled}}class="disabled"{{/if}}><a href="?p={{n}}">Next</a></li>
{{/paginate}}
</ul>
</div>
module.exports = function(pagination, options) {
var type = options.hash.type || 'middle';
var ret = '';
var pageCount = Number(pagination.total);
var page = Number(pagination.page);
var limit;
if (options.hash.limit) limit = +options.hash.limit;
//page pageCount
var newContext = {};
switch (type) {
case 'middle':
if (typeof limit === 'number') {
var i = 0;
var leftCount = Math.ceil(limit / 2) - 1;
var rightCount = limit - leftCount - 1;
if (page + rightCount > pageCount)
leftCount = limit - (pageCount - page) - 1;
if (page - leftCount < 1)
leftCount = page - 1;
var start = page - leftCount;
while (i < limit && i < pageCount) {
newContext = { n: start };
if (start === page) newContext.active = true;
ret = ret + options.fn(newContext);
start++;
i++;
}
}
else {
for (var i = 1; i <= pageCount; i++) {
newContext = { n: i };
if (i === page) newContext.active = true;
ret = ret + options.fn(newContext);
}
}
break;
case 'previous':
if (page === 1) {
newContext = { disabled: true, n: 1 }
}
else {
newContext = { n: page - 1 }
}
ret = ret + options.fn(newContext);
break;
case 'next':
newContext = {};
if (page === pageCount) {
newContext = { disabled: true, n: pageCount }
}
else {
newContext = { n: page + 1 }
}
ret = ret + options.fn(newContext);
break;
}
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment