Increment a variable in a Template

 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
'''
usage
{% ++ <var_name> %}
For example
{% ++ a %}
'''

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_var)

class IncrementVarNode(template.Node):

    def __init__(self, var_name):
        self.var_name = var_name

    def render(self,context):
        try:
            value = context[self.var_name]
            context[self.var_name] = value + 1
            return u""
        except:
            raise template.TemplateSyntaxError("The variable does not exist.")

More like this

  1. counter templatetag by bcurtu 4 years, 5 months ago
  2. Django Incremental Counter Tag by gwrtheyrn 2 years, 4 months ago
  3. Simple template tag to do |stringformat filter with format from a variable by leopd 3 years ago
  4. Template tag: Group variables into list by Killarny 5 years, 1 month ago
  5. assigning many partially deviant variables by justinlilly 6 years, 10 months ago

Comments

dhana (on June 5, 2013):

It is working Nice..

#

(Forgotten your password?)