
Untitled
By: a guest on
May 11th, 2012 | syntax:
None | size: 1.18 KB | hits: 75 | expires: Never
Django Template - Increment the value of a variable
{% set counter = 0 %}
{% for object in object_list %}
{% if object.attr1 == list1.attr1 and object.attr2 = list2.attr2 %}
<li><a href="{{ object.get_absolute_url }}"> Link {{counter++}} </a></li>
{% endif %}
{% endfor %}
new_lst = filter(lambda x: x.attr0 == attr0 and x.attr1 == attr1, lst)
{% for object in new_lst %}
<li><a href="{{ object.get_absolute_url }}"> Link {{ forloop.counter }} </a></li>
{% endfor %}
class IncrementVarNode(template.Node):
def __init__(self, var_name):
self.var_name = var_name
def render(self,context):
value = context[self.var_name]
context[self.var_name] = value + 1
return u""
def increment_var(parser, token):
parts = token.split_contents()
if len(parts) < 2:
raise template.TemplateSyntaxError("'increment' tag must be of the form: {% increment <var_name> %}")
return IncrementVarNode(parts[1])
register.tag('increment', increment_var)
class Counter:
count = 0
def increment(self):
self.count += 1
def decrement(self):
self.count -= 1
def double(self):
self.count *= 2