Skip to content

Instantly share code, notes, and snippets.

@kindlycat
Created October 11, 2016 21:10
Show Gist options
  • Save kindlycat/7fb41c1ba6077114f21266f7b8a16ef2 to your computer and use it in GitHub Desktop.
Save kindlycat/7fb41c1ba6077114f21266f7b8a16ef2 to your computer and use it in GitHub Desktop.
Implement simple jinja2 extension for django el_pagination (endless_pagination fork)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from jinja2 import nodes
from jinja2.ext import Extension
from el_pagination.templatetags.el_pagination_tags import paginate as el_paginate, ShowPagesNode
class Paginate(Extension):
tags = {'paginate'}
contents = None
paginate_node = None
def __init__(self, environment):
super(Paginate, self).__init__(environment)
environment.extend(el_pagination={})
def parse(self, parser):
paginator_args = []
lineno = parser.stream.current.lineno
while parser.stream.current.type != 'block_end':
current = next(parser.stream)
paginator_args += [str(current.value)]
lineno = current.lineno
self.contents = ' '.join(paginator_args)
self.paginate_node = el_paginate(self, self)
call = self.call_method('_render', [nodes.ContextReference()])
return [
nodes.CallBlock(call, [], [], [], lineno=lineno),
nodes.Assign(
nodes.Name('endless', 'store'),
nodes.Getitem(
nodes.EnvironmentAttribute('el_pagination'),
nodes.Const('endless'),
'load'
),
lineno=lineno
),
nodes.Assign(
nodes.Name(self.paginate_node.var_name, 'store'),
nodes.Getitem(
nodes.EnvironmentAttribute('el_pagination'),
nodes.Const(self.paginate_node.var_name),
'load'
),
lineno=lineno
),
]
def _render(self, context, caller=None):
ctx = context.get_all()
self.paginate_node.render(ctx)
self.environment.el_pagination.update({
'endless': ctx['endless'],
self.paginate_node.var_name: ctx[self.paginate_node.var_name],
})
return ''
class ShowPages(Extension):
tags = {'show_pages'}
def parse(self, parser):
lineno = next(parser.stream).lineno
call = self.call_method('_render', [nodes.ContextReference()], lineno=lineno)
return [nodes.Output([call], lineno=lineno)]
def _render(self, context):
ctx = context.get_all()
ctx.update(self.environment.el_pagination)
return ShowPagesNode().render(ctx)
@LennyLip
Copy link

It really helps! Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment