forloop Object

Used inside of a for loop block, provides data about the collection being looped over and the current iteration of the loop.

Attributes

Attribute Required Description
first Yes Returns true if it’s the first iteration of the for loop. Returns false if it is not the first iteration.
index Yes Returns the current index of the for loop, starting at 1.
index0 Yes Returns the current index of the for loop, starting at 0.
last Yes Returns true if it’s the last iteration of the for loop. Returns false if it is not the last iteration.
rindex Yes Returns forloop.index in reverse order.
rindex0 Yes Returns forloop.index0 in reverse order.
length Yes Returns the total number of iterations of the for loop.

Category

Contextual Objects

Description

This object is only available to code running inside a for loop block. Its purpose is to provide information about the loop’s current status and the collection that it’s looping through.

This code demonstrates many of the attributes available to the forloop object:

      {% for link in navigation %}
        {% if forloop.first %}
          <p>
            There are {{ forloop.length }} links in the navigation.
          </p>
        {% endif %}
      
        <a href="{{ link.path }}" id="link-{{ forloop.index }}" class="{% if forloop.last %}last{% endif %}">
          {{ link.title }}
        </a>
      {% endfor %}