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...
or have the same result with just one forloop
{% for user in users %}
{{ user.username }}{% if not loop.last %}, {% endif %}
{% endfor %}
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.
You can use map() filter… and fit everything in one line:
{{ users|map(u => u.username)|join(', ') }}
A shorter version of digital-message's idea:
{% for user in users %}
{{ user.username ~ (not loop.last ? ', ') }}
{% endfor %}
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