-
-
Save fission6/4164144 to your computer and use it in GitHub Desktop.
Django templatetag to output the current page's querystring updated with the specified values including context variables.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
register = template.Library() | |
class UpdateQuerystringNode(template.Node): | |
def __init__(self, **kwargs): | |
self.kwargs = kwargs | |
def render(self, context): | |
query_dict = context['request'].GET.copy() | |
for k, v in self.kwargs.items(): | |
try: | |
variable = template.Variable(v).resolve(context) | |
except template.VariableDoesNotExist: | |
variable = v | |
finally: | |
query_dict[k] = variable | |
return query_dict.urlencode() | |
@register.tag | |
def update_querystring(parser, token): | |
""" | |
From /?foo=bar, {% update_querystring foo=baz %} | |
will output foo=baz. | |
or use a context variable | |
{% update_querystring foo=request.user %} | |
foo=whatever | |
where whatever is the current user's username. | |
""" | |
bits = token.split_contents() | |
return UpdateQuerystringNode(**dict([bit.split('=') for bit in bits[1:]])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment