The For Loop and Scope

Code

January 8, 2020

One of the most common routine in Twig templates is the for .. endfor loop. It is the easiest way to iterate over all instances of an array or object in order to do something with the data.

Let’s imagine we have a group of regular posts from the normal posts post-type. A regular loop looks like this:

{% for item in posts %}
   <h2>{{ item.title }}</h2>
    {{ item.content }}
{% endfor %}

But what does that do, really? That’s fairly easy to break down.

The first line breaks down the posts variable in individual posts, and in this particular example we ask it to store each iteration as the variable item.

We could have asked it store it as variable name i or single, or some other made up name. Just make sure you pick a new, unique variable name.

The last line tells it when to end the for-loop. The code will not exit the loop until the end is reached. Unlike php or other programming languages, twig does not have a method to exit the loop prematurely.

Loop scope

Everything that happens in between the for-endfor loop has a certain scope. variables that didn’t exist BEFORE they entered the loop can be created, but will be destroyed when the loop exits. That’s why we need to pick a variable name that’s new and unique. The variable item is recreated over and over again and destroyed on the last exit as if it never existed.

Loop variable

Besides the loop scope (when variables live), there is also a loop variable. The variable can be used to keep track of the number of items that already have been shown, or perform mathematical expressions.

{% for item in posts %}
    <h2>Item #{{ loop.index }}: {{ item.title }}</h2>
    {{ item.content }}
{% endfor %}

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife.
Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.