Last active
July 6, 2020 17:22
-
-
Save leonsmith/5501345 to your computer and use it in GitHub Desktop.
Pagination range, used to limit huge pagination objects
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
from django import template | |
register = template.Library() | |
@register.filter | |
def pagination_range(obj, current=1, limit=10): | |
""" | |
Used with pagination page_range object when you have a lot of pages | |
> obj = range(100) | |
> pagination_limit(obj, 1) | |
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
> pagination_limit(obj, 6) | |
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
> pagination_limit(obj, 7) | |
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11] | |
> pagination_limit(obj, 9) | |
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13] | |
> pagination_limit(obj, 99) | |
[91, 92, 93, 94, 95, 96, 97, 98, 99, 100] | |
Use within a template with a paginator: | |
{% for page in obj_list.paginator.page_range|pagination_limit:obj_list.number %} | |
{{ page }} | |
{% endfor %} | |
""" | |
left = (limit / 2) + 1 | |
right = limit / 2 | |
total = len(obj) | |
if limit % 2 == 0: | |
right -= 1 | |
if current < left: | |
return obj[:limit] | |
if current > total - right: | |
return obj[total-limit:] | |
return obj[current-left:current+right] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@lxmmxl56 this was written 7 years ago so was python 2.7 only which used int division by default 👍