for, break, and continue Tags

Allows you to iterate over an array and execute code for each item in the array.

Description

for loops iterate over an array and allow you to execute code for each item in the array.

      {% for link in navigation.links %}
        <a href="{{ link.path }}">
          {{ link.title }}
        </a>
      {% endfor %}
      

Output

      <a href="/">
        Home
      </a>
      <a href="/products">
        Products
      </a>
      <a href="/about">
        About Us
      </a>
      <a href="/contact">
        Contact Us
      </a>
      

You can also provide a range of numbers using surrounding parentheses and 2 dots between the numbers in the range:

      {% for i in (1..5) %}
        {{ i }}
      {% endfor %}
      

Output

1 2 3 4 5
      {% assign max = 10 %}
      
      {% for i in (1..max) %}
        {{ i }}
      {% endfor %}
      

Output

1 2 3 4 5 6 7 8 9 10

break allows you to interrupt the for loop and exit out of it entirely:

Example: only show the first 5 links
      {% assign looplimit = 5 %}
      
      {% for link in navigation.links %}
        {% if forloop.index > looplimit %}
          {% break %}
        {% else %}
          <a href="{{ link.path }}">
            {{ link.title }}
          </a>
        {% endif %}
      {% endfor %}
      

continue allows you to skip to the next iteration of the loop:

Example: only show links after the first 5
      {% assign looplimit = 5 %}
      
      {% for link in navigation.links %{
        {% if forloop.index < looplimit %}
          <a href="{{ link.path }}">
            {{ link.title }}
          </a>
        {% else %}
          {% continue %}
        {% endif %}
      {% endfor %}
      

Parameters

limit

integer Limits the number of iterations through the loop.

      {% for link in navigation.links limit: 3 %}
        {{ link.title }}
      {% endfor %}
      
offset

integer Starts looping at a given index.

      {% for link in navigation.links offset: 2 %}
        {{ link.title }}
      {% endfor %}
      
reversed

boolean Reverses the order of the loop.

      {% for link in navigation.links reversed %}
        {{ link.title }}
      {% endfor %}