Add parameters to the current url

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

Nicodemus (on March 19, 2008):

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

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.