{% for %}

October CMS Documentation Docs

{% for %}

The {% for %} and {% endfor %} tags will loop over each value in a collection. A collection can be either an array or an object implementing the Traversable interface.

<ul>
    ___TWIG0___
        <li>___TWIG1___</li>
    ___TWIG2___
</ul>

You can also access both keys and values:

<ul>
    ___TWIG0___
        <li>___TWIG1___: ___TWIG2___</li>
    ___TWIG3___
</ul>

If the collection is empty, you can render a replacement block by using else:

<ul>
    ___TWIG0___
        <li>___TWIG1___</li>
    ___TWIG2___
        <li><em>There are no users found</em></li>
    ___TWIG3___
</ul>

# Looping a collection

If you do need to iterate over a collection of numbers, you can use the .. operator:

___TWIG0___
    - ___TWIG1___
___TWIG2___

The above snippet of code would print all numbers from 0 to 10.

It can also be useful with letters:

___TWIG0___
    - ___TWIG1___
___TWIG2___

The .. operator can take any expression at both sides:

___TWIG0___
    - ___TWIG1___
___TWIG2___

# Adding a condition

Unlike in PHP there is no function to break or continue in a loop, however you can still filter the collection. The following example skips all the users which are not active:

<ul>
    ___TWIG0___
        <li>___TWIG1___</li>
    ___TWIG2___
</ul>

# The loop variable

Inside of a for loop block you can access some special variables:

VariableDescription
loop.indexThe current iteration of the loop. (1 indexed)
loop.index0The current iteration of the loop. (0 indexed)
loop.revindexThe number of iterations from the end of the loop (1 indexed)
loop.revindex0The number of iterations from the end of the loop (0 indexed)
loop.firstTrue if first iteration
loop.lastTrue if last iteration
loop.lengthThe number of items in the collection
loop.parentThe parent context
___TWIG0___
    ___TWIG1___ - ___TWIG2___
___TWIG3___