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)

More like this

  1. Generic object_detail view filterable by multiple url values by jlorich 2 years, 11 months ago
  2. Add GET parameter tag by marltu 3 years, 9 months ago
  3. Fix duplicate first page of paginated results by muhuk 4 years, 7 months ago
  4. Persistent Params Decorator by achimnol 4 years, 8 months ago
  5. Url query string template tag (qurl) by pricco 7 months, 2 weeks ago

Comments

Ludwik Trammer (on February 16, 2010):

If you want to be able to pass variables from template into the template tag you may use the following version:

from django.template import Library, Node, resolve_variable, TemplateSyntaxError, Variable

register = Library()

class AddParameter(Node):
  def __init__(self, varname, value):
    self.varname = Variable(varname)
    self.value = Variable(value)

  def render(self, context):
    req = Variable('request').resolve(context)
    params = req.GET.copy()
    params[self.varname.resolve(context)] = self.value.resolve(context)
    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)

Sample usage:

{% addurlparameter 'sort' variable %}

#

(Forgotten your password?)