Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Filters batch
You are reading the documentation for Twig 2.x. Switch to the documentation for Twig 1.x. 3.x.
Warning Twig version 2.x end of maintenance is scheduled for December 2023.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

batch

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:

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 column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>

The above example will be rendered as:

1
2
3
4
5
6
7
8
9
10
11
12
<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</td>
        <td>No item</td>
        <td>No item</td>
    </tr>
</table>

Arguments

  • size: The size of the batch; fractional numbers will be rounded up
  • fill: Used to fill in missing items
  • preserve_keys: Whether to preserve keys or not
Website powered by Symfony and Twig, deployed on
The Twig logo is © 2010-2024 Symfony