Filtering and splicing an array in Twig

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 instance:

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 users where the field ageis 42, and then return the nameusers field as an array. Then I can pass this array in join(<br>)to print a single name per line.

For example, if age was 42, I would expect Twig to output:

Fred<br>
Alice

Is it possible to do this in Twig out of the box, or do I need to write my own filter? I'm not sure how to describe what I want in a few words, so maybe someone else wrote a filter, but I can’t find it by doing a search.

+5
3

, , . :

for each user
  create empty array of matches
  if current user matches criteria then
    add user to matches array
join array of matches

Twig:

{% 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 array Traversable , user.name , []. user.name raw, <br> &lt;br&gt; ( , , , ).

+3

for (.... in....) if, :

{% for user in users if user.age == 42 %}
    {{ user.name }}{{ !loop.last ? '<br>' }}
{% endfor %}
+2
{% for user in users %}
    {% if user.age == 42  %}
        {{ user.name|e }}<br>
    {% endif %}
{% endfor %}

{% set aUserMatchingCreteria %}
{% for user in users %}
    {% if user.age == 42  %}
        {% aUserMatchingCreteria = aUserMatchingCreteria|merge(user.name) %}
    {% endif %}
{% endfor %}

{{ aUserMatchingCreteria|join('<br>') }}
+1

Source: https://habr.com/ru/post/1667029/


All Articles