用树枝包裹 html 中的多行
Wrapping multiple rows in html with twig
所以我使用 twig 将数组中的一堆实体呈现到页面,我想知道是否可以将它们的每个块包装在 html 中?
例如,如果我有 100 个实体,并且我想用 class "page" 将每 10 个实体包装在 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>
或者您甚至可以使用简单的 if..else
语句使用 loop.index
variable:
{% 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
更清楚。
所以我使用 twig 将数组中的一堆实体呈现到页面,我想知道是否可以将它们的每个块包装在 html 中?
例如,如果我有 100 个实体,并且我想用 class "page" 将每 10 个实体包装在 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>
或者您甚至可以使用简单的 if..else
语句使用 loop.index
variable:
{% 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
更清楚。