Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 11th, 2012  |  syntax: None  |  size: 1.18 KB  |  hits: 75  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Django Template - Increment the value of a variable
  2. {% set counter = 0 %}
  3. {% for object in object_list %}
  4.     {% if object.attr1 == list1.attr1 and object.attr2 = list2.attr2 %}
  5.         <li><a href="{{ object.get_absolute_url }}"> Link {{counter++}} </a></li>
  6.      {% endif %}
  7. {% endfor %}
  8.        
  9. new_lst = filter(lambda x: x.attr0 == attr0 and x.attr1 == attr1, lst)
  10.        
  11. {% for object in new_lst %}
  12.    <li><a href="{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li>
  13. {% endfor %}
  14.        
  15. class IncrementVarNode(template.Node):
  16.  
  17.     def __init__(self, var_name):
  18.         self.var_name = var_name
  19.  
  20.     def render(self,context):
  21.         value = context[self.var_name]
  22.         context[self.var_name] = value + 1
  23.         return u""
  24.  
  25. def increment_var(parser, token):
  26.  
  27.     parts = token.split_contents()
  28.     if len(parts) < 2:
  29.         raise template.TemplateSyntaxError("'increment' tag must be of the form:  {% increment <var_name> %}")
  30.     return IncrementVarNode(parts[1])
  31.  
  32. register.tag('increment', increment_var)
  33.        
  34. class Counter:
  35.     count = 0
  36.  
  37.     def increment(self):
  38.         self.count += 1
  39.  
  40.     def decrement(self):
  41.         self.count -= 1
  42.  
  43.     def double(self):
  44.         self.count *= 2