Join property values of a list of objects in twig

symfony, twig

Solution

You could use..

{% set usernames = [] %}

{% for user in users %}
    {% set usernames = usernames|merge([user.username]) %}
{% endfor %}

{{ usernames|join(', ') }}

Not the prettiest though.

You could always make a custom twig filter to do it.

Problem

Is it possible to join the values of properties of a list of objects for displaying it? Something like: ``` {{ users|join(', ', username) }} ``` Where `users` are objects, having a `getUsername()` method. I suppose `join` doesn't take an additional argument, but is there a workaround to achieve something similar? I can not use the `__toString()` function, as it represents something else...

Original source