Skip to content

Instantly share code, notes, and snippets.

@arahaya
Last active December 12, 2015 08:39
Show Gist options
  • Save arahaya/4746161 to your computer and use it in GitHub Desktop.
Save arahaya/4746161 to your computer and use it in GitHub Desktop.
[django, jinja2, coffin] Add query string parameters to current URL
from jinja2 import nodes
from jinja2.ext import Extension
class UrlAddQueryExtension(Extension):
"""Add query string parameters to the current URL
This is a Jinja2 version of http://djangosnippets.org/snippets/2882/
targeted to work for django+coffin.
The django request object must be included in the context.
usage:
{% url_add_query page=pager.next_page_number() %}
"""
tags = set(['url_add_query'])
def parse(self, parser):
stream = parser.stream
tag = stream.next()
kwargs = []
while not stream.current.test_any('block_end', 'name:as'):
if stream.current.test('name') and stream.look().test('assign'):
key = nodes.Const(stream.next().value)
stream.skip()
value = parser.parse_expression()
kwargs.append(nodes.Pair(key, value, lineno=key.lineno))
return nodes.Output([
self.call_method('_render', args=[nodes.Name('request', 'load'), nodes.Dict(kwargs)]),
]).set_lineno(tag.lineno)
def _render(self, request, kwargs):
get = request.GET.copy()
get.update(kwargs)
path = '%s?' % request.path
for query, val in get.items():
path += '%s=%s&' % (query, val)
return path[:-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment