0

how to increment value of a variable in a template..??

{% for s in list%}
     {% for subject in s%}
             {% for sub in subject %}

                    <div id="{{ sub| getid:i }}"></div> 
                    # here i want to increment the value of i 
             {% endfor %}
      {% endfor %}
{% endfor %}
username
  • 4,258
  • 1
  • 16
  • 26
Arihant Nahata
  • 1,802
  • 2
  • 19
  • 30

3 Answers3

4

If you want to increase i over all nested loops, you can pass another stateful context variable, such as i=itertools.count(), and in the template, you use

<div id="{{ sub| getid:i.next }}"></div>

The Django documentation on the template language design states the philosophy of the template language is that

the template system is meant to express presentation, not program logic.

And this often means you cannot manipulate state directly with filters. To achieve state changes, you will have to create your own stateful variables whose state can be altered via a function call.

eddie_c
  • 3,403
  • 1
  • 16
  • 6
3

Using a template for loop? You may try this using:

forloop.counter

see the docs here: http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs

Implementation:

{% for s in list%} 
  {% for subject in s%} 
    {% for sub in subject %}
                <div id="{{ sub| getid:forloop.counter+(forloop.parentloop.counter - 1)*total_iterations_inner_loop+(forloop.parentloop.parentloop.counter-1)*total_iterations_mid_loop*total_iterations_inner_loop }}"></div> 
         {% endfor %}
  {% endfor %}
{% endfor %}
crodjer
  • 13,384
  • 9
  • 38
  • 52
0

check out http://docs.djangoproject.com/en/dev/ref/templates/builtins/#add

sjh
  • 2,236
  • 1
  • 18
  • 21
  • this would only return the addition of the values but wouldn't change the variable's value..!! – Arihant Nahata Nov 15 '10 at 17:24
  • This will only change the output. It won't change the value of variable `i`. – eddie_c Nov 15 '10 at 17:25
  • you may try this: http://stackoverflow.com/questions/2376511/how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-templates for accessing the parent loop counter and use the add tag to update the innermost loop according to outer ones. – crodjer Nov 15 '10 at 17:33
  • what i want is, every time
    is encountered , then i should have new value, starting from 0 , 1 , 2 and so on...
    – Arihant Nahata Nov 15 '10 at 17:39