假设我在数组中将一些名为"people"的数据转换为这样的树枝模板:
firstname | surname | colour
Fred Smith Blue
James Holmes Red
Sarah Fisher Blue
Chrstine Jenkins Yellow
Sid Wells Red
Cory Simpson Blue
Laura Jones Yellow
Run Code Online (Sandbox Code Playgroud)
有了这些数据,我需要通过"颜色"列对它们进行分组.通过基于颜色包裹用户周围的div.例如
<div class="colour_container">
Fred Smith - Blue<br>
Sarah Fisher - Blue<br>
Cory Simpson - Blue<br>
</div>
<div class="colour_container">
James Holmes - Red<br>
Sid Wells - Red<br>
</div>
<div class="colour_container">
Christine Jenkins - Yellow<br>
Laura Jones - Yellow<br>
</div>
Run Code Online (Sandbox Code Playgroud)
现在如果我使用一个twig循环,它会将div放在每个名称周围,而不是按颜色对它们进行分组.什么是获得上述输出的最简单方法?我已经在循环中尝试了各种各样的东西,但我正在努力.
{% for p in people %}
<div class="colour_container">
{{ p.firstname }} {{ p.surname }} - {{ p.colour }}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我需要它以某种方式循环遍历唯一的颜色值,然后循环遍历属于该颜色的名称.
我最近遇到过类似的问题.我做了扩展并将其作为开源发布.它引入了lambda表达式和|group_by过滤器.
https://github.com/dpolac/twig-lambda
有了它,你可以简单地写:
{% for colour, group in people|group_by(=> _.colour) %}
<div class="colour_container">
{% for person in group %}
{{ person.firstname }} {{ person.surname }} - {{ person.colour }}
{% endfor %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)