Grouping collections
Often, we want to group pages or files by various criteria, for example, print a list of blog posts grouped by year, group upcoming events by month, a list of authors by character in the alphabeth, a set of images by photographer and so on. With Kirby's groupBy()
and group($callback
) methods, this is pretty easy.
Let's look at some examples to fuel your imagination.
The field you want to group by must exist and contain a value. If necessary, filter your collection before using the methods to prevent errors.
Simple grouping by field values
The most straighforward way to group collections is by using the groupBy()
method. Let's suppose our imaginary collection of projects had a year field and we wanted to group these projects by year.
This gives us a a bi-dimensional collection with items for each year.
Now let's see how to output this collection object:
As you can see, we use two foreach loops here, one for the criterium we group by (here the year), and then a second one for the items that belong to each group.
Complex grouping
Sometimes, the simple groupBy()
method has its limits. For example, suppose in the above example we didn't have a simple year field, but a normal date field, but still wanted to group by year. That wouldn't be possible. The group()
method with a callback to the rescue.
We first define the callback function, which returns the date in year format. Then we pass that function as parameter to the group()
method.
Here is another interesting example that allows us to group by points in time or time ranges, to which we assign category names to group by like "today", "this week", or "this month".
Combining methods for more complex grouping scenarios
We can make things even more complex. Have a look at this example:
In this example we want to group our items by a combination of two date fields, from
and to
. We use the map()
method with a callback to create a "virtual" field called eventDate
, then we pass this field to the groupBy()
method.
Grouping files
We can use both group()
and groupBy()
with files.
Example for groupBy()
In this example, we group all images of all subpages by the photographer field and output a small thumbnail for each group:
Example with group($callback)
The group()
with callback example works in the same way as with pages collections: