--- /dev/null
+``batch``
+=========
+
+.. versionadded:: 1.12.3
+ The batch filter was added in Twig 1.12.3.
+
+The ``batch`` filter "batches" items by returning a list of lists with the
+given number of items. If you provide a second parameter, it is used to fill
+missing items:
+
+.. code-block:: jinja
+
+ {% 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>
+
+The above example will be rendered as:
+
+.. code-block:: jinja
+
+ <table>
+ <tr>
+ <td>a</td>
+ <td>b</td>
+ <td>c</td>
+ </tr>
+ <tr>
+ <td>d</td>
+ <td>e</td>
+ <td>f</td>
+ </tr>
+ <tr>
+ <td>g</td>
+ <td>No item</td>
+ <td>No item</td>
+ </tr>
+ </table>
new Twig_SimpleFilter('split', 'twig_split_filter'),
new Twig_SimpleFilter('sort', 'twig_sort_filter'),
new Twig_SimpleFilter('merge', 'twig_array_merge'),
+ new Twig_SimpleFilter('batch', 'twig_array_batch'),
// string/array filters
new Twig_SimpleFilter('reverse', 'twig_reverse_filter', array('needs_environment' => true)),
return constant($constant);
}
+
+/**
+ * Batches item.
+ *
+ * @param array $items An array of items
+ * @param integer $size The size of the batch
+ * @param string $fill A string to fill missing items
+ *
+ * @return array
+ */
+function twig_array_batch($items, $size, $fill = null)
+{
+ if ($items instanceof Traversable) {
+ $items = iterator_to_array($items, false);
+ }
+
+ $result = array_chunk($items, $size, true);
+
+ if (null !== $fill) {
+ $last = count($result) - 1;
+ while (count($result[$last]) < $size) {
+ $result[$last][] = $fill;
+ }
+ }
+
+ return $result;
+}
--- /dev/null
+--TEST--
+"batch" filter
+--TEMPLATE--
+<table>
+{% for row in items|batch(3, '') %}
+ <tr>
+ {% for column in row %}
+ <td>{{ column }}</td>
+ {% endfor %}
+ </tr>
+{% endfor %}
+</table>
+--DATA--
+return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'))
+--EXPECT--
+<table>
+ <tr>
+ <td>a</td>
+ <td>b</td>
+ <td>c</td>
+ </tr>
+ <tr>
+ <td>d</td>
+ <td>e</td>
+ <td>f</td>
+ </tr>
+ <tr>
+ <td>g</td>
+ <td>h</td>
+ <td>i</td>
+ </tr>
+ <tr>
+ <td>j</td>
+ <td></td>
+ <td></td>
+ </tr>
+</table>