Loop or Iterate over Arrays with Scriptlets
Scriptlets allow for
loops to be used in your templates for looping over an array collection. You can also loop through a range of numbers using the 1..n
syntax.
for loop
Convert a string to an array, print the initial 2 items"
{% assign fruitArray = "Apple, Orange, Mango" | split: ", " %}
{% for fruit in fruitArray limit: 2 %}
{? fruit ?}
{% endfor %}
// Output: Apple Orange
Convert a string to an array, print 2 items, begin the loop at the specified index (offset)
{% assign alphabets = "a, b, c, d, e, f, g" | split: ", " %}
{% for character in alphabets limit: 2 offset: 3 %}
{? character ?}
{% endfor %}
// Output: d e
Run a loop n
number of times using a range of numbers
{% for i in (1..5) %}
{? i ?}
{% endfor %}
// Output: 1 2 3 4 5
Run a for loop, exit break
the loop when a value, 7 in this case, is found
{% for i in (5..10) %}
{% if i == 7 %}
{% break %}
{% else %}
{? i ?} exists!
{% endif %}
{% endfor %}
Run a for loop, skip certain values
{% for i in (1..10) %}
{% if i == 4 %}
{% continue %}
{% elsif i == 9 %}
{% continue %}
{% else %}
{? i ?} exists
{% endif %}
{% endfor %}
Run a for loop from 5 to 10, and print whether the value is even or odd
{% for i in (5..10) %}
{% assign isEven = i | modulo: 2 %}
{% if isEven == 0 %}
{? i ?} is even
{% else %}
{? i ?} is odd.
{% endif %}
{% endfor %}
increment
Creates a new number variable, and increases or decreases its value by one every time it is called. The first value is 0.
The current value is {% increment count %}
The incremented value is {% increment count %}
{% decrement count %}
The decremented value is {% decrement count %}