我想将以下一行从PHP转换为twig我尝试了很多方法但没有用,任何人都可以指导我怎么办...
<?php foreach (array_chunk($images, 4) as $image) { ?>
和
<?php if ($image['type'] == 'image') { ?>
答案 0 :(得分:3)
batch filter 将原始数组拆分为多个块。 查看此示例以获得更好的说明:
{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{#The first param to batch() is the size of the batch#}
{#The 2nd param is the text to display for missing items#}
{% for row in items|batch(3, 'No item') %}
<tr>
{% for column in row %}
<td>{{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
这将呈现为:
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
<tr>
<td>g</td>
<td>No item</td>
<td>No item</td>
</tr>
</table>
答案 1 :(得分:2)
array_chunk
内嵌twig
作为slice
- 过滤器
{% for image in images|slice(0,4) %}
{% if image.type == 'image' %}
{# I am an image #}
{% endif %}
{% endfor %}
您可以通过移动if
for-loop
来缩短上述示例
{% for image in images|slice(0,4) if image.type == 'image' %}
{# I am an image #}
{% endfor %}