所以我使用 twig 将数组中的一堆实体渲染到页面,我想知道是否可以将它们的每个 block 包装在 html 中?
例如,如果我有 100 个实体,并且我想将每 10 个实体包装在类为“page”的 div 中,这可以用 twig 实现还是我需要其他东西?
我一直在研究循环、模数等,但无法弄清楚。有什么建议吗?
我目前正在使用 for 循环将它们放到页面上,并尝试找出如何用 html 包装它们的组。
最佳答案
您可以为此使用batch
过滤器。来自 Twig
documentation :
The batch filter "batches" items by returning a list of lists with the given number of items. A second parameter can be provided and used to fill in missing items:
{% 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
variable来使用简单的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
更加清晰。
关于php - 用 twig 在 html 中包裹多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33501743/