If you want to display a list separated by comma you could just prepare a comma separated list in php in the controller and pass it to the twig template. But that does not result in very clean code, so in this post you can read up on how to create a list separated with commas in twig directly.

How to display a comma separated list in Twig

If we have passed an array – lets call it myArray – from the controller to a twig template and want to print every element of it in a comma separated list the naive approach would be:

<!-- bad approach-->
{% for element in myArray %}
    {{ element.someString }},
{% endfor %}

<!-- example in (myArray): ['test1','test2','test3'] -->
<!-- example out: 'test1, test2, test3, ' -->

But with this approach we will have a trailing comma which we cannot get rid of (as twig does not allow php code with which we could do this easily). There are two good solutions:

<!-- good approach #1 -->
{{ myArray|join(',') }}

<!-- example in (myArray): ['test1','test2','test3'] -->
<!-- example out: 'test1, test2, test3' -->

This will join the elements of the array and separate them with a comma. The strings that are used if the array contains objects are defined by the toString method of the object.

If we do not want to use the toString method of objects to define what string is printed, we have to use another solution:

<!-- good approach #2 -->
{% for element in myArray %}
    <a href="#element.someString">visit {{ element.someString }}</a> {{ loop.last ? '' : ', ' }}
{% endfor %}

<!-- example in (myArray): ['object1','object2','object3'] objects have getSomeString method which returns 'visit testN' -->
<!-- example out: 'visit test1, visit test2, visit test3' -->

That did it! Now we have what we wanted: A comma separated list without trailing comma. More about the loop variable can be found in the twig documents about the for keyword (there is not really a lot you can do with it, but it does have two index methods, for those who prefer starting at 1 and those who prefer starting at 0. I would have preferred useful methods instead, but that might just be me).