Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated list in twig

Tags:

php

twig

What is the shortest (and clearest) way to add comma after each element of the list except the last one?

{% for role in user.roles %}
    {{ role.name }},
{% endfor %}

This example will add comma after all lines, including the last one.

like image 268
Dmitry Avatar asked Aug 09 '13 07:08

Dmitry


4 Answers

Don't know about shortest but this could be clear. Try the following to add comma after all lines in the loop except the last one:

{% for role in user.roles %}
    {{ role.name }}
    {% if not loop.last %},{% endif %}
{% endfor %}

Shorter version as suggested in comments:

{% for role in user.roles %}
    {{ role.name }}
    {{ not loop.last ? ',' }}
{% endfor %}
like image 137
vee Avatar answered Oct 23 '22 22:10

vee


This works with Symfony 2.3.x but should work with every 2.x version:

{{ user.roles|join(', ') }}
like image 36
Frieder Avatar answered Oct 23 '22 22:10

Frieder


{{- not loop.last ? ',' : '' -}}

like image 2
Mario Hernandez Avatar answered Oct 23 '22 21:10

Mario Hernandez


{{ user.roles|column('title')|join(', ') }}

like image 2
user1730452 Avatar answered Oct 23 '22 23:10

user1730452