<commit_before>---
title: A Date Batch Filter for Twig
summary: A date batch filter for Twig
---
In Twig there is a filter called batch.

> The batch filter "batches" items by returning a list of lists with the given number of items.
>
> <cite>[Twig Documentation][twig_docs]</cite>

For the articles pages of this site I needed a similar thing. I needed to be able to group articles by the year and month of their publish date. I wrote a new filter that I call date_batch. It takes two parameters. The first is the property or the key in each item of the the collection being filtered. The second is the format that the items will be grouped by. This could be the year and month, "Y-m", which is the default, or any other format accepted by DateTime::createFromFormat and DateTime::format. It returns an associative array where the keys are the formatted date converted to a Unix time stamp&mdash;so the keys can then be reformatted using the date filter&mdash;and the values are collections of items from the original collection.

```markup
<!-- twig -->
{% for year_month, batched_entries in entries|date_batch('published_on') %}
    <section><commit_msg>Use twig syntax<commit_after>---
title: A Date Batch Filter for Twig
summary: A date batch filter for Twig
---
In Twig there is a filter called batch.

> The batch filter "batches" items by returning a list of lists with the given number of items.
>
> <cite>[Twig Documentation][twig_docs]</cite>

For the articles pages of this site I needed a similar thing. I needed to be able to group articles by the year and month of their publish date. I wrote a new filter that I call date_batch. It takes two parameters. The first is the property or the key in each item of the the collection being filtered. The second is the format that the items will be grouped by. This could be the year and month, "Y-m", which is the default, or any other format accepted by DateTime::createFromFormat and DateTime::format. It returns an associative array where the keys are the formatted date converted to a Unix time stamp&mdash;so the keys can then be reformatted using the date filter&mdash;and the values are collections of items from the original collection.

```twig
<!-- twig -->
{% for year_month, batched_entries in entries|date_batch('published_on') %}
    <section>
{'fraction_non_alphanumeric': 0.0613126079447323, 'fraction_numerical': 0.0, 'mean_word_length': 4.326436781609195, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7144243', 'n_tokens_mistral': 599, 'n_tokens_neox': 582, 'n_words': 361}