Tutorials References Exercises Videos Menu
Create Website Get Certified Upgrade

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.

{% 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

<ul>
  {% for x in members %}
    <li style='background-color:{% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' %}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

If the cycle reaches the end of the arguments, it starts over:

Example

<ul>
  {% for x in members %}
    <li style='background-color:{% cycle 'lightblue' 'pink' %}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Cycle Arguments as Variable

In the first example the argument values were 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:

<ul>
  {% for x in members %}
    {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor silent %}
    <li style='background-color:{{ bgcolor }}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

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:

<ul>
  {% for x in members %}
    {% cycle 'lightblue' 'pink' 'yellow' 'coral' 'grey' as bgcolor %}
    <li style='background-color:{{ bgcolor }}'>
      {{ x.firstname }}
    </li>
  {% endfor %}
</ul> 
Run Example »

Reset Cycle

You can force the cycle to restart by using the {% resetcycle %} tag:

Example

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> 
Run Example »