Last active
December 2, 2024 13:20
-
-
Save trantorLiu/5924389 to your computer and use it in GitHub Desktop.
Handlebars pagination 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('pagination', function(currentPage, totalPage, size, options) { | |
var startPage, endPage, context; | |
if (arguments.length === 3) { | |
options = size; | |
size = 5; | |
} | |
startPage = currentPage - Math.floor(size / 2); | |
endPage = currentPage + Math.floor(size / 2); | |
if (startPage <= 0) { | |
endPage -= (startPage - 1); | |
startPage = 1; | |
} | |
if (endPage > totalPage) { | |
endPage = totalPage; | |
if (endPage - size + 1 > 0) { | |
startPage = endPage - size + 1; | |
} else { | |
startPage = 1; | |
} | |
} | |
context = { | |
startFromFirstPage: false, | |
pages: [], | |
endAtLastPage: false, | |
}; | |
if (startPage === 1) { | |
context.startFromFirstPage = true; | |
} | |
for (var i = startPage; i <= endPage; i++) { | |
context.pages.push({ | |
page: i, | |
isCurrent: i === currentPage, | |
}); | |
} | |
if (endPage === totalPage) { | |
context.endAtLastPage = true; | |
} | |
return options.fn(context); | |
}); |
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
// currentPage = 1, pageCount = 25, size = 5 | |
[1] 2 3 4 5 > | |
// currentPage = 16, pageCount = 25, size = 5 | |
< 14 15 [16] 17 18 > |
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
{{#pagination currentPage pageCount size}} | |
<div class="pagination"> | |
{{#unless startFromFirstPage}} | |
<a href="#"><</a> | |
{{/unless}} | |
{{#each pages}} | |
{{#if isCurrent}} | |
[<a href="#">{{page}}</a>] | |
{{/if}} | |
{{#unless isCurrent}} | |
<a href="#">{{page}}</a> | |
{{/unless}} | |
{{/each}} | |
{{#unless endAtLastPage}} | |
<a href="#">></a> | |
{{/unless}} | |
</div> | |
{{/pagination}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, how can implement this with multiple tabs? thank you