= Paginator Tag =
This is a very basic inclusion tag which builds on the variables already set on the context when paginating with the [http://www.djangoproject.com/documentation/generic_views/#django-views-generic-list-detail-object-list generic object_list view] to allow you to create pagination controls which display first/last page links and links for a number of pages adjacent to the current page.
The following additional context variables are created:
* '''page_numbers''': A list of page numbers (in ascending order) which should be displayed, including the current page number.
* '''show_first''': A boolean representing whether a first page link should be shown - this will be '''True''' if the first page number doesn't appear in '''page_numbers'''.
* '''show_last''': A boolean representing whether a last page link should be shown - this will be '''True''' if the last page number doesn't appear in '''page_numbers'''.
== Usage ==
The tag can take a single argument, which specifies the number of adjacent page links. The default is 2.
{{{
{% if is_paginated %}
{% paginator %}
{% endif %}
{% if is_paginated %}{% paginator 4 %}
{% endif %}
}}}
== Code ==
{{{
from django import template
register = template.Library()
def paginator(context, adjacent_pages=2):
"""Adds pagination context variables for first, adjacent and next page links
in addition to those already populated by the object_detail generic view."""
page_numbers = [n for n in \
range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) \
if n > 0 and n <= context["pages"]]
return {
"hits": context["hits"],
"results_per_page": context["results_per_page"],
"page": context["page"],
"pages": context["pages"],
"page_numbers": page_numbers,
"next": context["next"],
"previous": context["previous"],
"has_next": context["has_next"],
"has_previous": context["has_previous"],
"show_first": 1 not in page_numbers,
"show_last": context["pages"] not in page_numbers,
}
register.inclusion_tag("paginator.html", takes_context=True)(paginator)
}}}
Sample paginator.html:
{{{
{% spaceless %}
{{ pages }} Pages
{% if show_first %}«{% endif %}
{% if has_previous %}<{% endif %}
{% for num in page_numbers %}
{% ifequal num page %}
{{ num }}
{% else %}
{{ num }}
{% endifequal %}
{% endfor %}
{% if has_next %}>{% endif %}
{% if show_last %}»{% endif %}
{% endspaceless %}
}}}
paginator.js, used by the above:
{{{
var Paginator =
{
jumpToPage: function(pages)
{
var page = prompt("Enter a number between 1 and " + pages + " to jump to that page", "");
if (page != undefined)
{
page = parseInt(page, 10)
if (!isNaN(page) && page > 0 && page <= pages)
{
window.location.href = "?page=" + page;
}
}
}
};
}}}