I have an array of user records (0 indexed, from a database query), each of which contains an array of fields (indexed by field name). For example:
Array
(
[0] => Array
(
[name] => Fred
[age] => 42
)
[1] => Array
(
[name] => Alice
[age] => 42
)
[2] => Array
(
[name] => Eve
[age] => 24
)
)
In my Twig template, I want to get all the users where the age
field is 42 and then return the name
field of those users as an array. I can then pass that array to join(<br>)
to print one name per line.
For example, if the age was 42 I would expect Twig to output:
Fred<br>
Alice
Is this possible to do in Twig out of the box, or would I need to write a custom filter? I'm not sure how to describe what I want in a couple of words so it may be that someone else has written a filter but I can't find it by searching.
If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default). Internally, Twig uses the PHP explode or str_split (if delimiter is empty) functions for string splitting.
Filters in Twig can be used to modify variables. Filters are separated from the variable by a pipe symbol. They may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.
Accessing array elements Twig as a parameter can receive array. To access a specific element of array you can use regular php array access bracket notation {{ array[key] }} .
Final solution was a mix of what has been posted so far, with a couple of changes. The pseudocode is:
for each user
create empty array of matches
if current user matches criteria then
add user to matches array
join array of matches
Twig code:
{% set matched_users = [] %}
{% for user in users %}
{% if user.age == 42 %}
{% set matched_users = matched_users|merge([user.name|e]) %}
{% endif %}
{% endfor %}
{{ matched_users|join('<br>')|raw }}
merge
will only accept an array
or Traversable
as the argument so you have to convert the user.name
string to a single-element array by enclosing it in []
. You also need to escape user.name
and use raw
, otherwise <br>
will be converted into <br>
(in this case I want the user's name escaped because it comes from an untrusted source, whereas the line break is a string I've specified).
In twig you can merge the for ( .... in ....) with the if condition like :
{% for user in users if user.age == 42 %}
{{ user.name }}{{ !loop.last ? '<br>' }}
{% endfor %}
Edit: This syntax is deprecated, and we are advised to use |filter
as a replacement for the for...if
syntax.
Twig Filter: filter (The name of the filter is filter)
Twig Deprecated Features
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