Login

Add parameters to the current url

Author:
johan-de-taeye
Posted:
August 9, 2007
Language:
Python
Version:
.96
Score:
3 (after 11 ratings)

Often a page contains a link to itself, with an additional parameter for in the url. E.g. to sort the page in a different way, to export the data into another format, etc... This tag makes this easy, avoiding any hardcoded urls in your pages.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 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 %}

#

Please login first before commenting.