Skip to content

Commit ed6b315

Browse files
Documentation for array_group_by filter and function
1 parent 857f8bc commit ed6b315

File tree

1 file changed

+35
-0
lines changed
  • pages/03.themes/04.twig-tags-filters-functions/02.filters

1 file changed

+35
-0
lines changed

pages/03.themes/04.twig-tags-filters-functions/02.filters/docs.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,41 @@ Wrapper for PHP `array_unique()` that removes duplicates from an array.
2525

2626
`['foo', 'bar', 'foo', 'baz']|array_unique` <i class="fa fa-long-arrow-right"></i> **{{ print_r(['foo', 'bar', 'foo', 'baz']|array_unique) }}**
2727

28+
### `array_group_by`
29+
30+
Groups items in an array or collection by a specified property or callback function. This filter is particularly useful for organizing blog posts, products, or any collection of items by common attributes like date, category, author, or custom criteria.
31+
32+
**Basic usage with a property name:**
33+
34+
`collection|array_group_by('category')` <i class="fa fa-long-arrow-right"></i> Groups items by their 'category' property
35+
36+
**Example: Grouping by taxonomy category**
37+
38+
{% verbatim %}
39+
```twig
40+
{# Prepare collection with category #}
41+
{% set collection_with_category = [] %}
42+
{% for post in page.collection() %}
43+
{% set category = post.taxonomy.category|first ?: 'uncategorized' %}
44+
{% set collection_with_category = collection_with_category|merge([{
45+
post: post,
46+
category: category
47+
}]) %}
48+
{% endfor %}
49+
50+
{# Group by category #}
51+
{% set posts_by_category = collection_with_category|array_group_by('category') %}
52+
53+
{# Display grouped posts #}
54+
{% for category, posts in posts_by_category %}
55+
<h3>{{ category|capitalize }}</h3>
56+
{% for item in posts %}
57+
<div>{{ item.post.title }}</div>
58+
{% endfor %}
59+
{% endfor %}
60+
```
61+
{% endverbatim %}
62+
2863
### `base32_encode`
2964

3065
Performs a base32 encoding on variable

0 commit comments

Comments
 (0)