You can define a split character with the help of the split filter. It divides the string and creates an array from it, which can be used by foreach .
{% foreach item in 'one,two,three'|split(',') %}
{{ item }} <br />
{% endforeach %}
In this example, the split character is , (comma). item loops through all elements from the array and lists them one by one. If you include the HTML<br>
tag, every element will be displayed in a new row:
one
two
three
You can also include a limit argument. There is a difference between working with positive and negative numbers. An example for a positive number is 2, where the first element will be displayed as a standalone string and the remaining elements will become one string.
{% foreach item in "one,two,three,four,five"|split(',',2) %}
{{ item }} <br />
{% endforeach %}
Result
one
two,three,four,five
On the other hand, if the limit is -1, the very last element will not be returned, all the other elements will be displayed.
{% foreach item in "one,two,three,four,five"|split(',',-1) %}
{{ item }} <br />
{% endforeach %}
Result
one
two
three
four
If the limit is zero, one string will be created from all elements in the array.
{% foreach item in "one,two,three,four,five"|split(',',0) %}
{{ item }} <br />
{% endforeach %}
Result
one,two,three,four,five
If you don't define a split character, instead you include an empty string, the array will be split at every character.
{% foreach item in "123"|split('') %}
{{ item }} <br />
{% endforeach %}
Result
1
2
3
If you add a limit to the empty string delimiter, the array will be split at this specific number.
{% foreach item in "112233"|split('',2) %}
{{ item }} <br />
{% endforeach %}
Result
11
22
33