I had two-subpages with Files
collections. I needed to take the first 6 files from A
and then append the shuffled remainder of A
and B
files. This could have been accomplished with more loops in the template, but I wanted to compose a single Files
collection and have a single loop in the template.
- Page
- Subpage A
- Subpage B
I discovered that the Pages
collection as a nice add() method that as per this post, but the Files
collection doesn’t have any facilities to append to it.
I came up with this hacky way of appending to a Files collection. It relies on the fact that kirby collections have an internal array called data
that contains the items of the collection. So, if you append from the data
array of one collection to the data
collection of another, you in add to that collection.
This is probably unwise, because I think there is potential for collisions when merging arrays. I believe (and someone can correct me) that filenames are used as keys in a Files
collection. If so, then appending an identical filename with array_merge will cause one of the files to disappear from the array.
Anyway, it got done what I needed to get done. I’m frustrated that kirby doesn’t allow you to explicitly create multiple file collections for a page. Maybe it’s due to the flat-file database approach.
####Here is an example of how to merge two Files
collections into one:
// get the Files collections of sub-pages
$files_A = $page->children()->find('subpage-a')->files();
$files_B = $page->children()->find('subpage-b')->files();
// create an empty Files collection, with mandatory reference to the current page
$new_array = new Files($page);
// append files of A & B to $new_array
$new_array->data = array_merge($new_array->data, $files_A->data);
$new_array->data = array_merge($new_array->data, $files_B->data);
// $new_array now contains files from A & B