Login

Add multiple parameters to the current url

Author:
cschand
Posted:
July 1, 2008
Language:
Python
Version:
.96
Tags:
url templatetags parameter
Score:
1 (after 1 ratings)

Add multiple parameters to the current url.<br /> Usage:<br /> {% addparam name1 value1 name2 value2 %}<br /> or<br /> {% addparam "name1" value1 "name2" value2 %}<br />

variable can be use inplace of names and values<br />
example: <br />`{% addparam "view" message.id %}`
 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django.template import Library, Node, resolve_variable, TemplateSyntaxError

register = Library()

class AddParameters(Node):
  def __init__(self, vars):
    self.vars = vars
   
  def render(self, context):
    req = resolve_variable('request',context)
    params = req.GET.copy()

    for i in range(0, len(self.vars), 2):
      key = self.vars[i].resolve(context)
      if key == '': key = self.vars[i]      
      value = self.vars[i+1].resolve(context)
      if value == '': value = self.vars[i+1]
      params[key] = value

    return '%s?%s' % (req.path, params.urlencode())

def addparam(parser, token):
  """
  Add multiple parameters to current url 

  Usage:
    {% addparam name1 value1 name2 value2 %}
                      or
    {% addparam "name1" value1 "name2" value2 %}    

    variable can be use inplace of names and values
    example: {% addparam "view" message.id %}

  """

  bits = token.contents.split(' ')
  if len(bits) < 2:
    raise TemplateSyntaxError, "'%s' tag requires atleast two arguments" % bits[0]
  
  if len(bits)%2 != 1:
    raise TemplateSyntaxError, "The arguments must be pairs"
 
  vars = [parser.compile_filter(bit) for bit in bits[1:]]
  return AddParameters(vars)
  
register.tag('addparam', addparam)

More like this

  1. Page numbers with ... like in Digg by Ciantic 6 years, 2 months ago
  2. Support for {% macro %} tags in templates, version 2 by mludvig 7 years, 11 months ago
  3. Multiple-Submit-Button Widget for Choice Field by Archatas 6 years, 11 months ago
  4. Routing urls.py By Convention by doconix 3 years, 1 month ago
  5. better paginator template tag by amitu 6 years, 8 months ago

Comments

Please login first before commenting.