Django cycle Tag
Cycles
The cycle
tag allows you to do different tasks for different iterations.
The cycle
tag takes arguments, the first iteration uses the first argument, the second iteration uses the second argument etc.
1 |
{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' %} |
If you want to have a new background color for each iteration, you can do that with the cycle
tag:
Example
1 2 3 4 5 6 7 |
<ul> {% for x in members %} <li style='background-color:{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' %}'> {{ x.firstname }} </li> {% endfor %} </ul> |
If the cycle reaches the end of the arguments, it starts over:
Example
1 2 3 4 5 6 7 |
<ul> {% for x in members %} <li style='background-color:{% cycle 'lightblue' 'pink' %}'> {{ x.firstname }} </li> {% endfor %} </ul> |
Cycle Arguments as Variable
In the first example the argument values was displayed directly in the cycle, but you can also keep the argument values in a variable, and use it later:
Example
Store the color values in a variable named bgcolor, and use it as a background color later in the loop:
1 2 3 4 5 6 7 8 |
<ul> {% for x in members %} {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor silent %} <li style='background-color:{{ bgcolor }}'> {{ x.firstname }} </li> {% endfor %} </ul> |
Did you notice the silent
keyword? Make sure you add this, or else the argument values will be displayed twice in the output:
Example
Same example as above, but without the silent
keyword:
1 2 3 4 5 6 7 8 |
<ul> {% for x in members %} {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor %} <li style='background-color:{{ bgcolor }}'> {{ x.firstname }} </li> {% endfor %} </ul> |
Reset Cycle
You can force the cycle to restart by using the {% resetcycle %}
tag:
Example
Restart the cycle after 3 cycles:
1 2 3 4 5 6 7 8 9 10 11 |
<ul> {% for x in members %} {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor silent %} {% if forloop.counter == 3 %} {% resetcycle %} {% endif %} <li style='background-color:{{ bgcolor }}'> {{ x.firstname }} </li> {% endfor %} </ul> |