X-Git-Url: https://git.mdrn.pl/django-pagination.git/blobdiff_plain/79b65b1914b1db437200f57df24f76653d0451cc..4b2ba62948c5104fc3cae8d24face3c4bf7378df:/linaro_django_pagination/templatetags/pagination_tags.py diff --git a/linaro_django_pagination/templatetags/pagination_tags.py b/linaro_django_pagination/templatetags/pagination_tags.py index e8331c2..995edc3 100644 --- a/linaro_django_pagination/templatetags/pagination_tags.py +++ b/linaro_django_pagination/templatetags/pagination_tags.py @@ -1,11 +1,11 @@ # Copyright (c) 2008, Eric Florenzano -# Copyright (C) 2010, 2011 Linaro Limited +# Copyright (c) 2010, 2011 Linaro Limited # All rights reserved. -# +# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: -# +# # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above @@ -15,7 +15,7 @@ # * Neither the name of the author nor the names of other # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. -# +# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -29,12 +29,21 @@ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -from django import template from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.paginator import Paginator, InvalidPage from django.http import Http404 -from django.template import TOKEN_BLOCK +from django.template import ( + Context, + Library, + Node, + TOKEN_BLOCK, + TemplateSyntaxError, + Variable, + loader, +) +from django.template.loader import select_template +from django.utils.text import unescape_string_literal # TODO, import this normally later on from linaro_django_pagination.settings import * @@ -51,7 +60,7 @@ def do_autopaginate(parser, token): # Check whether there are any other autopaginations are later in this template expr = lambda obj: (obj.token_type == TOKEN_BLOCK and \ len(obj.split_contents()) > 0 and obj.split_contents()[0] == "autopaginate") - multiple_paginations = len(filter(expr, parser.tokens)) > 0 + multiple_paginations = len([tok for tok in parser.tokens if expr(tok)]) > 0 i = iter(token.split_contents()) paginate_by = None @@ -60,50 +69,49 @@ def do_autopaginate(parser, token): orphans = None word = None try: - word = i.next() + word = next(i) assert word == "autopaginate" - queryset_var = i.next() - word = i.next() + queryset_var = next(i) + word = next(i) if word != "as": paginate_by = word try: paginate_by = int(paginate_by) except ValueError: pass - word = i.next() + word = next(i) if word != "as": orphans = word try: orphans = int(orphans) except ValueError: pass - word = i.next() + word = next(i) assert word == "as" - context_var = i.next() + context_var = next(i) except StopIteration: pass if queryset_var is None: - raise template.TemplateSyntaxError( + raise TemplateSyntaxError( "Invalid syntax. Proper usage of this tag is: " - "{%% autopaginate QUERYSET [PAGINATE_BY] [ORPHANS]" - " [as CONTEXT_VAR_NAME] %%}" - ) + "{% autopaginate QUERYSET [PAGINATE_BY] [ORPHANS]" + " [as CONTEXT_VAR_NAME] %}") return AutoPaginateNode(queryset_var, multiple_paginations, paginate_by, orphans, context_var) -class AutoPaginateNode(template.Node): +class AutoPaginateNode(Node): """ Emits the required objects to allow for Digg-style pagination. - + First, it looks in the current context for the variable specified, and using - that object, it emits a simple ``Paginator`` and the current page object + that object, it emits a simple ``Paginator`` and the current page object into the context names ``paginator`` and ``page_obj``, respectively. - + It will then replace the variable specified with only the objects for the current page. - + .. note:: - + It is recommended to use *{% paginate %}* after using the autopaginate tag. If you choose not to use *{% paginate %}*, make sure to display the list of available pages, or else the application may seem to be buggy. @@ -114,24 +122,24 @@ class AutoPaginateNode(template.Node): paginate_by = DEFAULT_PAGINATION if orphans is None: orphans = DEFAULT_ORPHANS - self.queryset_var = template.Variable(queryset_var) + self.queryset_var = Variable(queryset_var) if isinstance(paginate_by, int): self.paginate_by = paginate_by else: - self.paginate_by = template.Variable(paginate_by) + self.paginate_by = Variable(paginate_by) if isinstance(orphans, int): self.orphans = orphans else: - self.orphans = template.Variable(orphans) + self.orphans = Variable(orphans) self.context_var = context_var self.multiple_paginations = multiple_paginations def render(self, context): - if self.multiple_paginations or "paginator" in context: + if self.multiple_paginations or getattr(context, "paginator", None): page_suffix = '_%s' % self.queryset_var else: page_suffix = '' - + key = self.queryset_var.var value = self.queryset_var.resolve(context) if isinstance(self.paginate_by, int): @@ -168,41 +176,76 @@ class AutoPaginateNode(template.Node): return u'' +class PaginateNode(Node): + + def __init__(self, template=None): + self.template = template + + def render(self, context): + template_list = ['pagination/pagination.html'] + new_context = paginate(context) + if self.template: + template_list.insert(0, self.template) + return loader.render_to_string(template_list, new_context, + context_instance = context) + + + +def do_paginate(parser, token): + """ + Emits the pagination control for the most recent autopaginate list + + Syntax is: + + paginate [using "TEMPLATE"] + + Where TEMPLATE is a quoted template name. If missing the default template + is used (paginate/pagination.html). + """ + argv = token.split_contents() + argc = len(argv) + if argc == 1: + template = None + elif argc == 3 and argv[1] == 'using': + template = unescape_string_literal(argv[2]) + else: + raise TemplateSyntaxError( + "Invalid syntax. Proper usage of this tag is: " + "{% paginate [using \"TEMPLATE\"] %}") + return PaginateNode(template) + + def paginate(context, window=DEFAULT_WINDOW, margin=DEFAULT_MARGIN): """ Renders the ``pagination/pagination.html`` template, resulting in a Digg-like display of the available pages, given the current page. If there are too many pages to be displayed before and after the current page, then elipses will be used to indicate the undisplayed gap between page numbers. - + Requires one argument, ``context``, which should be a dictionary-like data structure and must contain the following keys: - + ``paginator`` A ``Paginator`` or ``QuerySetPaginator`` object. - + ``page_obj`` - This should be the result of calling the page method on the + This should be the result of calling the page method on the aforementioned ``Paginator`` or ``QuerySetPaginator`` object, given the current page. - + This same ``context`` dictionary-like data structure may also include: - + ``getvars`` A dictionary of all of the **GET** parameters in the current request. This is useful to maintain certain types of state, even when requesting a different page. - - ``pagination_template`` - A custom template to include in place of the default ``pagination/default.html`` - contents. - + Argument ``window`` is number to pages before/after current page. If window exceeds pagination border (1 and end), window is moved to left or right. - Argument ``margin``` is number of pages on start/end of pagination. + Argument ``margin``` is number of pages on start/end of pagination. Example: - window=2, margin=1, current=6 1 ... 4 5 [6] 7 8 ... 11 + window=2, margin=1, current=6 1 ... 4 5 [6] 7 8 ... 11 window=2, margin=0, current=1 [1] 2 3 4 5 ... window=2, margin=0, current=5 ... 3 4 [5] 6 7 ... window=2, margin=0, current=11 ... 7 8 9 10 [11] @@ -217,7 +260,6 @@ def paginate(context, window=DEFAULT_WINDOW, margin=DEFAULT_MARGIN): page_obj = context['page_obj'] page_suffix = context.get('page_suffix', '') page_range = paginator.page_range - pagination_template = context.get('pagination_template', 'pagination/default.html') # Calculate the record range in the current page for display. records = {'first': 1 + (page_obj.number - 1) * paginator.per_page} records['last'] = records['first'] + paginator.per_page - 1 @@ -261,9 +303,10 @@ def paginate(context, window=DEFAULT_WINDOW, margin=DEFAULT_MARGIN): if pages[-1] != paginator.num_pages: pages.append(None) - to_return = { + new_context = { 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': getattr(settings, "STATIC_URL", None), + 'disable_link_for_first_page': DISABLE_LINK_FOR_FIRST_PAGE, 'display_disabled_next_link': DISPLAY_DISABLED_NEXT_LINK, 'display_disabled_previous_link': DISPLAY_DISABLED_PREVIOUS_LINK, 'display_page_links': DISPLAY_PAGE_LINKS, @@ -272,7 +315,6 @@ def paginate(context, window=DEFAULT_WINDOW, margin=DEFAULT_MARGIN): 'page_obj': page_obj, 'page_suffix': page_suffix, 'pages': pages, - 'pagination_template': pagination_template, 'paginator': paginator, 'previous_link_decorator': PREVIOUS_LINK_DECORATOR, 'records': records, @@ -282,15 +324,16 @@ def paginate(context, window=DEFAULT_WINDOW, margin=DEFAULT_MARGIN): if 'page%s' % page_suffix in getvars: del getvars['page%s' % page_suffix] if len(getvars.keys()) > 0: - to_return['getvars'] = "&%s" % getvars.urlencode() + new_context['getvars'] = "&%s" % getvars.urlencode() else: - to_return['getvars'] = '' - return to_return + new_context['getvars'] = '' + return new_context except (KeyError, AttributeError): - return {} + pass + + return context -register = template.Library() -register.inclusion_tag( - 'pagination/pagination.html', takes_context=True)(paginate) +register = Library() +register.tag('paginate', do_paginate) register.tag('autopaginate', do_autopaginate)