在 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 将只接受 array 或 Traversable 作为参数,因此您必须转换 user.name 通过将字符串包含在 [] 中,将其转换为单元素数组.还需要转义user.name并使用raw,否则<br>会被转换成<br>(在这种情况下,我希望用户名转义,因为它来自不受信任的来源,而换行符是我指定的字符串).
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).
相关文章