在Twig中过滤和拼接数组 [英] Filtering and splicing an array in Twig

查看:214
本文介绍了在Twig中过滤和拼接数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
        )

)

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

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.

例如,如果年龄是42岁,我希望Twig输出:

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

Fred<br>
Alice

这是否可以在Twig中直接使用,还是需要编写自定义过滤器?我不确定如何用几个词来描述我想要的内容,因此可能是其他人编写了过滤器,但我无法通过搜索找到它.

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.

推荐答案

最终解决方案是到目前为止已发布内容的组合,并进行了一些更改.伪代码为:

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

小枝代码:

{% 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仅接受arrayTraversable作为参数,因此您必须通过将user.name字符串括在[]中来将其转换为单元素数组.您还需要转义user.name并使用raw,否则<br>将转换为&lt;br&gt;(在这种情况下,我希望用户名转义,因为它来自不受信任的来源,而换行符是字符串我已指定).

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).

这篇关于在Twig中过滤和拼接数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆