Exploding a string into an array in a Twig template

Published on 2020-02-10 • Modified on 2020-02-10

The function is not explode like in PHP. Instead, we can use the split filter (that internally uses the explode or str_split PHP functions) like this:


{% set fruits = 'apple,banana,orange' %}
<h3>Fruits : {{ fruits }}</h3>
<ul>
    {% for fruit in fruits|split(',') %}
        <li>{{ fruit }}</li>
    {% endfor %}
</ul>
HTML demo of the snippet

Fruits : apple,banana,orange

  • apple
  • banana
  • orange

 More on Stackoverflow   Read the doc  Run on 3v4l.org  Random snippet

  Work with me!