在Twig中过滤和拼接数组

pwa*_*ing 5 php arrays twig silex

我有一组用户记录(0索引,来自数据库查询),每个记录包含一个字段数组(按字段名称索引).例如:

Array
(
    [0] => Array
        (
            [name] => Fred
            [age] => 42
        )

    [1] => Array
        (
            [name] => Alice
            [age] => 42
        )

    [2] => Array
        (
            [name] => Eve
            [age] => 24
        )

)
Run Code Online (Sandbox Code Playgroud)

在我的Twig模板中,我希望获得age字段为42的所有用户,然后将name这些用户的字段作为数组返回.然后,我可以传递该数组,join(<br>)以便每行打印一个名称.

例如,如果年龄为42岁,我会期望Twig输出:

Fred<br>
Alice
Run Code Online (Sandbox Code Playgroud)

这可以在Twig开箱即用,还是我需要编写自定义过滤器?我不确定如何用几个词来描述我想要的东西,所以可能是其他人写了一个过滤器,但我找不到它通过搜索.

Pau*_*rié 7

您可以在应用 for 循环的数组上应用过滤器,如下所示:

{% for u in user|filter((u) => u.age == 42) -%}
   <!-- do your stuff -->
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


pwa*_*ing 6

最终的解决方案是迄今为止发布的内容的混合,并进行了一些更改。伪代码是:

for each user
  create empty array of matches
  if current user matches criteria then
    add user to matches array
join array of matches
Run Code Online (Sandbox Code Playgroud)

树枝代码:

{% 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 }}
Run Code Online (Sandbox Code Playgroud)

merge将只接受arrayorTraversable作为参数,因此您必须通过将user.name字符串包含在[]. 您还需要转义user.name并使用raw,否则<br>将转换为&lt;br&gt;(在这种情况下,我希望将用户名转义,因为它来自不受信任的来源,而换行符是我指定的字符串)。


小智 5

在 Twig 中,您可以将 for ( .... in ....) 与 if 条件合并,例如:

{% for user in users if user.age == 42 %}
    {{ user.name }}{{ !loop.last ? '<br>' }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

编辑:不推荐使用此语法,建议我们使用|filterfor...if语法作为替代。

Twig Filter:过滤器过滤器的名称是filter)

Twig 已弃用的功能