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!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil