Twig provides many filters that mimic the basic features of PHP that are easy to understand for front-end developers.
One of those filters is a split filter that allows you to split a delimited string by a single character, returning a repeating array.
{% set tags = "First, Second, Third" | split(",") %}
{# tags contains ['First', 'Second', 'Third'] #}
{# Print every tag in a new line #}
{% for tag in tags %}
{{ tag }}
{% endfor %}
You can limit the length of the result array providing it as second argument, for example, to limit the length of the array to only 3 items:
{% set tags = "first,second,third,fourth,fifth"|split(',', 3) %}
{# tags contains ["first", "second", "third,fourth,fifth"]#}
{% for tag in tags %}
{{ tag }}
{% endfor %}
If the delimiter is empty, the string will be split into chunks of the same size:
{% set tags = "abcd"|split('') %}
{# tags contains ["a", "b", "c", "d"]#}
{% for tag in tags %}
{{ tag }}
{% endfor %}
Whenever there’s no delimiter (an empty string), the limit argument will specify the size of the chunk:
{% set tags = "aabbccdd"|split('', 2) %}
{# tags contains ["aa", "bb", "cc", "dd"]#}
{% for tag in tags %}
{{ tag }}
{% endfor %}
Hello, I enjoy reading through your article. I like to write a little comment to support you.
Thanks
“Great content as always! Thanks a lot.”
“This is what exactly I was looking for🙏
Thanks a lot buddy for sharing.,its really easy to understand and implement.”
Very detailed explanation. Thanks for sharing it.
I love this articles. Thanks for sharing.