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. Let's say our page collection has a start date (from
) and an end date (to
), and we want to group all items with the same start and end date.
For this case, we can either use a callbackback like above that returns the combined date, or we create a page model method called eventDate
. In this case, let's use a page model.
Since our children use the event
blueprint, we create a model called EventPage
:
Now we can group by this 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: