# tag
from django import template
register = template.Library()
from django.template.defaulttags import url
class PaginatorNode(template.Node):
def __init__(self, adjacent_pages=2, urltokens='', pagearg='', parser=None):
self.adjacent_pages = adjacent_pages
self.urltokens = urltokens
self.pagearg = pagearg
self.parser = parser
def get_page_link(self, context, page):
spaceorcomma = string.find(self.urltokens, ' ') != -1 and ',' or ' '
c = 'url %s%s%s' % (self.urltokens, spaceorcomma, "%s=%s" % (self.pagearg, page))
new_tokens = template.Token(template.TOKEN_TEXT, c)
return {'number': page, 'link': url(self.parser, new_tokens).render(context)}
def render(self, context):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
page_numbers = [n for n in \
range(context['page'] - self.adjacent_pages, context['page'] + self.adjacent_pages + 1) \
if n > 0 and n <= context['pages']]
from django.template.loader import get_template
t = get_template('paginator.html')
paginatorcontext = template.Context({
'hits': context['hits'],
'results_per_page': context['results_per_page'],
'page': context['page'],
'pages': context['pages'],
'page_numbers': [self.get_page_link(context, n) for n in page_numbers],
'next': self.get_page_link(context, context['next']),
'previous': self.get_page_link(context, context['previous']),
'has_next': context['has_next'],
'has_previous': context['has_previous'],
'show_first': 1 not in page_numbers,
'first': self.get_page_link(context, 1),
'show_last': context['pages'] not in page_numbers,
'last': self.get_page_link(context, context['pages'])
})
return t.render(paginatorcontext)
def paginator(parser, token):
bits = token.contents.split(' ')
lim = len(bits) == 4 and 3 or 4
urltokens = ' '.join(bits[2:lim])
return PaginatorNode(adjacent_pages=int(bits[1]), urltokens=urltokens, pagearg=bits[lim], parser=parser)
register.tag(paginator)
# paginator.html
"""
{% spaceless %}
{{ pages }} Pages
{% if show_first %}«{% endif %}
{% if has_previous %}<{% endif %}
{% for num in page_numbers %}
{% ifequal num.number page %}
{{ num.number }}
{% else %}
{{ num.number }}
{% endifequal %}
{% endfor %}
{% if has_next %}>{% endif %}
{% if show_last %}»{% endif %}
{% endspaceless %}
"""
# urls.py
('^tags/(?P[^/]+)/$', 'tagging.views.tagged_object_list', {'model': Image, 'paginate_by':3}, 'image_tag'),
('^tags/(?P[^/]+)/(?P\d+)/$', 'tagging.views.tagged_object_list', {'model': Image, 'paginate_by':3}, 'image_tag_paged'),