Loops

On this page

Overview

Below is a list of all the available attributes for the loop object


 
Name Description
forloop.first Returns true if it's the first iteration of the for loop.
forloop.index Returns the current index of the the for loop. It starts at 1.
forloop.index0 Returns the currenct index of the for loop, but this one starts at 0.
forloop.last Returns true if it's the last iteration of the for loop.
forloop.length Returns the number of iterations in the for loop.
 

for

Repeatedly executes a block of code. For a full list of attributes avalible within a for loop, see the table above.

 

{% for book in litterature.products %}
  {{ book.title }},
{% endfor %}

 
Advanced Potion-Making, Fantastic Beasts and Where to Find Them, A History of Magic

 


else

Specifies a fallback case for a for loop which will run if the loop has zero length.

 
{% for book in litterature.products %}
  {{ book.title }}
{% else %}
  There are no books.
{% endfor %}
 
There are no books.

 


break

Causes the loop to stop iterating when it encounters the break tag.

 

{% for i in (1..5) %}
  {% if i == 4 %}
    {% break %}
  {% else %}
    {{ i }}
  {% endif %}
{% endfor %}

 
1 2 3

 


continue

Causes the loop to skip the current iteration when it encounters the continue tag.

 

{% for i in (1..5) %}
  {% if i == 4 %}
    {% continue %}
  {% else %}
    {{ i }}
  {% endif %}
{% endfor %}

 
1 2 3   5

Updated: 2020-06-16