Filtering and splicing an array in Twig

馋奶兔 提交于 2019-12-12 11:07:46

问题


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.


回答1:


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 &lt;br&gt; (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).




回答2:


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 %}



回答3:


{% for user in users %}
    {% if user.age == 42  %}
        {{ user.name|e }}<br>
    {% endif %}
{% endfor %}

in alternative you can create an array of elements

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

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


来源:https://stackoverflow.com/questions/41702618/filtering-and-splicing-an-array-in-twig

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!