Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join property values of a list of objects in twig

Tags:

twig

symfony

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...

like image 554
Stivni Avatar asked Apr 05 '13 09:04

Stivni


4 Answers

or have the same result with just one forloop

{% for user in users %}
    {{ user.username }}{% if not loop.last %}, {% endif %}
{% endfor %}
like image 102
digital-message Avatar answered Sep 30 '22 06:09

digital-message


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.

like image 40
qooplmao Avatar answered Sep 30 '22 05:09

qooplmao


You can use map() filter… and fit everything in one line:

{{ users|map(u => u.username)|join(', ') }}
like image 45
gregmatys Avatar answered Sep 30 '22 06:09

gregmatys


A shorter version of digital-message's idea:

{% for user in users %}
    {{ user.username ~ (not loop.last ? ', ') }}
{% endfor %}
like image 36
insertusernamehere Avatar answered Sep 30 '22 06:09

insertusernamehere