Filtering and splicing an array in Twig(在 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).
这篇关于在 Twig 中过滤和拼接数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Twig 中过滤和拼接数组
基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
