如何在树枝中转换阵列块



我想将以下行从php转换为twig,我尝试了许多方法,但是没有人可以指导我如何做...

<?php foreach (array_chunk($images, 4) as $image) { ?>

<?php if ($image['type'] == 'image') { ?>

使用twig的内置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>

参考

array_chunk是内置的twig作为slice -Filter

{% 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 %}

文档

最新更新