Example usage in html template:
<a href="{% addurlparameter sort 1 %}">Sort on field 1</a>
<a href="{% addurlparameter output pdf %}">Export as pdf</a>
from django.template import Library, Node, resolve_variable, TemplateSyntaxError
register = Library()
class AddParameter(Node):
def __init__(self, varname, value):
self.varname = varname
self.value = value
def render(self, context):
req = resolve_variable('request',context)
params = req.GET.copy()
params[self.varname] = self.value
return '%s?%s' % (req.path, params.urlencode())
def addurlparameter(parser, token):
from re import split
bits = split(r'\s+', token.contents, 2)
if len(bits) < 2:
raise TemplateSyntaxError, "'%s' tag requires two arguments" % bits[0]
return AddParameter(bits[1],bits[2])
register.tag('addurlparameter', addurlparameter)
Comments
This is exactly what I was looking for, but here's a tip for anyone else that wants to use it. You have to use RequestContext() instead of just Context, and you have to have django.core.context_processors.request enabled in your TEMPLATE_CONTEXT_PROCESSORS which it is not by default. It's detailed in the docs at http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext.
-Nate
#
If you want to be able to pass variables from template into the template tag you may use the following version:
Sample usage:
#