用小树枝在html中包装多行


Wrapping multiple rows in html with twig

所以我使用trick将数组中的一组实体呈现到页面上,我想知道是否可以将它们的每一块都封装在html中?

例如,如果我有100个实体,并且我想用类"page"将每10个包裹在一个div中,那么用trick实现这一点可能吗?或者我需要其他东西吗?

我一直在玩循环、模数等,但搞不清楚。有什么建议吗?

我目前正在使用for循环将它们放到页面上,并试图找出如何用html包装它们的组。

您可以为此使用batch过滤器。来自Twig文档:

批处理过滤"批处理"项目,方法是返回带有给定项目数。第二个参数可以被提供并用于填写缺失项目:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

或者,您甚至可以使用loop.index变量使用简单的if..else语句:

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
<table>
{% for row in items %}
    {% if loop.index % 3 == 1 %}
    <tr>
    {% endif %}
        <td>{{ row }}</td>
    {% if loop.index % 3 == 0 or loop.last %}
    </tr>
    {% endif %}
{% endfor %}
</table>

正如您所看到的,使用batch更加清晰。