The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Where am I in the Twig Loop?

by Ryan Irelan

Twig offers special loop variables that makes it easy to know which iteration of the for-loop, for example, we are on. This allows us to do different styling, markup, or other condition-based things.

In Craft, we typically loop through our section entries like this:


{% for entry in craft.entries.section('news') %}
    {{ entry.title }} 
{% endfor %}

Twig loops through the Craft data and displays each entry retrieved from the News section.

To check if this is the first iteration of the loop, we can use a conditional and check against the loop.first variable from Twig.

A conditional in Craft allows us to control flow in the template. We use the if tag in Twig to make this happen. We can check if an expression evaluates to true:


{% for entry in craft.entries.section('news') %}
    {% if loop.first %}
        First!
    {% endif %}
    {{ entry.title }} 
{% endfor %}

In this example we’re testing if the loop.first expression is true. loop.first is one of six special loop variables made available to us from Twig (not Craft). This evaluates true if it is the first iteration of the for-loop. Otherwise it will evaluate false.

We’re not just limited to the loop.first variable. We can check for the current count, how many iterations until we reach the end of the loop (very handy!), and more.

Here are the other variations of loop:

  • loop.index - This is the count of the current iteration, starting at 1. Handy if you’re used to starting at 1 for counts or need to output it for something like table rows.
  • loop.index0 - Add a 0 and you get the count of the current iteration, starting at 0, instead of at 1. This is a more traditional way of counting iterations and how you would want to use it for for-loops.
  • loop.revindex - How many loops until the end? This variable will output the number of iterations left, starting at 1. If you want to start at zero, use the next variable.
  • loop.revindex0 - The same as the previous variable but starting at 0 instead of 1.
  • loop.last - A good way of knowing that your loop is about to end. Maybe you want to close a HTML tag or do something else before the loop is over. loop.last evaluates true if it is the last iteration of the loop.
  • loop.length - How many items are in the loop? This variable will output the total number of items so you know the total number of loops that will happen.

With the loop variable variations, you should need to set up a counter while iterating over data sets in Twig. Even you if need to start at 0 or 1, loop has you covered.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Filed Under: Craft CMS, Twig