batch
batch
过滤器通过返回包含给定数量项目的列表的列表来“批量处理”项目。可以提供第二个参数并用于填充缺失的项目
1 2 3 4 5 6 7 8 9 10 11
{% set items = ['a', 'b', 'c', 'd'] %}
<table>
{% for row in items|batch(3, 'No item') %}
<tr>
{% for index, column in row %}
<td>{{ index }} - {{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
上面的示例将渲染为
1 2 3 4 5 6 7 8 9 10 11 12
<table>
<tr>
<td>0 - a</td>
<td>1 - b</td>
<td>2 - c</td>
</tr>
<tr>
<td>3 - d</td>
<td>4 - No item</td>
<td>5 - No item</td>
</tr>
</table>
如果您选择将第三个参数 preserve_keys
设置为 false
,则键将在每次循环中重置。
1 2 3 4 5 6 7 8 9 10 11
{% set items = ['a', 'b', 'c', 'd'] %}
<table>
{% for row in items|batch(3, 'No item', false) %}
<tr>
{% for index, column in row %}
<td>{{ index }} - {{ column }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
上面的示例将渲染为
1 2 3 4 5 6 7 8 9 10 11 12
<table>
<tr>
<td>0 - a</td>
<td>1 - b</td>
<td>2 - c</td>
</tr>
<tr>
<td>0 - d</td>
<td>1 - No item</td>
<td>2 - No item</td>
</tr>
</table>
参数
size
: 批次的大小;小数将向上舍入fill
: 用于填充缺失的项目preserve_keys
: 是否保留键(默认为true
)