for
Loop over collections. for
loops can iterate over arrays, hashes, and ranges of integers.
Input
-
foo_array = ["apple", "banana"]
{% for item in foo_array %}{{ item }}{% endfor %}
Output
-
apple banana
break
Exit the loop
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{% for item in foo_array %}{% if item == 4 %}{% break %}{% else %}{{ item }}{% endif %}{% endfor %}
Output
-
1, 2, 3
continue
Skips the remaining code in the current for
loop and continues with the next.
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{% for item in foo_array %}{% if item == 4 %}{% continue %}{% else %}{{ item }}{% endif %}{% endfor %}
Output
-
1, 2, 3, 5, 6
for (parameters)
limit:#
Restrict how many items of the array are returned
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{% for item in foo_array limit:2 %}{{ item }}{% endfor %}
Output
-
1, 2
offset:#
Start the collection with the n
item.
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{% for item in foo_array offset:2 %}{{ item }}{% endfor %}
Output
-
3, 4, 5, 6
range
Define a range of numbers to loop through - can be defined by both literal and variable numbers.
Input
-
{% for i in (1..4) %}{{ i }}{% endfor %}
Output
-
1, 2, 3, 4
reversed
Return the array in reversed order
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{% for item in foo_array reversed %}{{ item }}{% endfor %}
Output
-
6, 5, 4, 3, 2, 1
Iterating a hash
When iterating a hash, item[0]
contains the key, and item[1]
contains the value
Input
-
{% for item in hash %}{{ item[0] }}:{{ item[1] }}{% endfor %}
Output
-
key:value
.first
Returns the first item in the array
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{{ foo_array.first }}
Output
-
1
.last
Returns the last item in the array
Input
-
foo_array = [1, 2, 3, 4, 5, 6]
{{ foo_array.last }}
Output
-
6
else
Define a range of numbers to loop through - can be defined by both literal and variable numbers.
Input
-
foo_array = []
{% for item in foo_array %}{{ item.title }}{% else %}There are no items!{% endfor %}
Output
-
There are no items!