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.
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 %}
This works with Symfony 2.3.x but should work with every 2.x version:
{{ user.roles|join(', ') }}
{{- not loop.last ? ',' : '' -}}
{{ user.roles|column('title')|join(', ') }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With