Use this template tag to get a paginator showing the first and last two pages w/ adjacent pages using ellipsis.
The page
parameter is a page of a Paginator
(typically the first but you can use whichever you want).
In case of 50 pages, while being on the 40th, it'll give you the following iterable of int
s (with settings.PAGINATOR_ADJACENT_PAGES = 2
):
(1, 2, 38, 39, 40, 41, 42, 49, 50)
You get the idea.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | from django import template
from django.conf import settings
from django.core.paginator import Page
register = template.Library()
@register.assignment_tag
def get_paginated_list(
page=None, adjacent_pages=settings.PAGINATOR_ADJACENT_PAGES):
"""
Generate a paginator list with ellipsis.
"""
# Sanity check
if type(page) is not Page or page.paginator.count == 0:
return None
paginator = page.paginator
num_pages = paginator.num_pages
if num_pages == 1:
return (1,)
start_page = max(page.number - adjacent_pages, 1)
end_page = min(page.number + adjacent_pages, num_pages)
print(start_page, end_page)
page_number_list = []
page_number_list.extend((
x for x in range(start_page, end_page + 1)))
if 2 not in page_number_list:
page_number_list.insert(0, 2)
page_number_list.insert(0, 1)
if num_pages - 1 not in page_number_list:
page_number_list.extend((num_pages - 1, num_pages))
return page_number_list
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.