HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
The cycle tag allows you to do different tasks for different iterations
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.
{% 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:
<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:
<ul>
{% for x in members %}
<li style='background-color:{% cycle 'lightblue' 'pink' %}'>
{{ x.firstname }}
</li>
{% endfor %}
</ul>
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:
Store the color values in a variable named bgcolor, and use it as a background color later in the loop:
<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:
Same example as above, but without the silent
keyword:
<ul>
{% for x in members %}
{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor %}
<li style='background-color:{{ bgcolor }}'>
{{ x.firstname }}
</li>
{% endfor %}
</ul>
You can force the cycle to restart by using the {% resetcycle %}
tag:
Restart the cycle after 3 cycles:
<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>