Commits

Anonymous committed a730a75

Added pagination helper

Comments (0)

Files changed (3)

gnocchi/tools/templatetags/__init__.py

Empty file added.

gnocchi/tools/templatetags/paginate.py

+
+from django import template
+from django.template.base import FilterExpression
+
+register = template.Library()
+
+@register.filter
+def querystring(qdict, pagenum):
+    '''Set the page number to that passed, and return the querystring'''
+    qdict['page'] = pagenum
+    return qdict.urlencode()
+
+def resolve(val, context):
+    if isinstance(val, FilterExpression):
+        return val.resolve(context)
+    return val
+
+class PaginateNode(template.Node):
+    def __init__(self, nodelist, querydict=None, span=5, leadin=3, leadout=3):
+        self.nodelist = nodelist
+        self.querydict = querydict
+        self.span = span
+        self.leadin = leadin
+        self.leadout = leadout
+
+    def render(self, context):
+        querydict = self.querydict
+        if not querydict:
+            querydict = context['request'].GET
+
+        page = context['page_obj']
+        paginator = context['paginator']
+
+        span = int(resolve(self.span, context))
+        leadin = int(resolve(self.span, context))
+        leadout = int(resolve(self.span, context))
+
+        start = max(1, page.number - (span // 2) )
+        stop = min(paginator.num_pages, page.number + (span // 2))
+
+        # Turn leadout into Nth from end
+        leadout = paginator.num_pages - leadout
+
+        # If we overlap the leadin, merge the leadin
+        if start <= leadin:
+            leadin = []
+            start = 1
+        else:
+            leadin = range(1, leadin)
+        # Same for the leadout
+        if stop >= leadout:
+            leadout = []
+            stop = paginator.num_pages
+        else:
+            leadout = range(leadout, paginator.num_pages)
+
+        context.update({
+            'querydict': querydict.copy(),
+            'page_range': range(start, stop+1),
+            'page': page,
+            'leadin': leadin,
+            'leadout': leadout,
+        })
+        output = self.nodelist.render(context)
+        context.pop()
+        return output
+
+@register.tag
+def paginate(parser, token):
+    bits = token.contents.split()
+    bits.pop(0)	# discard name
+    kwargs = {}
+    if bits:
+        if not '=' in bits[0]:
+            kwargs['querydict'] = bits.pop(0)
+        for bit in bits:
+            key, val = bit.split('=')
+            kwargs[key] = parser.compile_filter(val)
+    nodelist = parser.parse(('endpaginate',))
+    parser.delete_first_token()
+    return PaginateNode(nodelist, **kwargs)
 from setuptools import setup, find_packages
 
 setup( name='gnocchi-tools',
-    version = '1.1',
+    version = '1.1.1',
     description = 'Common tools used by Gnocchi apps',
     author = 'Curtis Maloney',
     author_email = 'curtis@tinbrain.net',