Add multiple 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
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 5 years ago
  2. Support for {% macro %} tags in templates, version 2 by mludvig 6 years, 8 months ago
  3. Multiple-Submit-Button Widget for Choice Field by Archatas 5 years, 8 months ago
  4. Routing urls.py By Convention by doconix 1 year, 10 months ago
  5. better paginator template tag by amitu 5 years, 6 months ago

Comments

(Forgotten your password?)