Dynamically extend a collection before rendering

If I created a collection (site/collections), is it possible to dynamically extend that collection later and save those additions?

What Iā€™m trying to achieve is to create a ā€œanchor navigationā€ helper. The helper first of all collects all H2 elements from the dynamic layouts and blocks and creates a collection containing the slugified id, href and text label. So far so good, I implemented that part and this works.

Now I have some static titles in the template which I want to add to this collection. Part of the logic for that would be:

$this->kirby()->collection('collection-name')->append($newItem->href(), $newItem);

I put this into a page model function which I can call with the title text I want to add to this collection, right from the template:

<?= page()->homeStdIdAndAddToToc('My static title') =?>

The complete logic of this function is to return a slugified value I can directly use as ID, and at the same time add this information to the anchor list collection, so the anchor list can be rendered later with the dynamically added static titles, and also the ones collected from the block fields I already have in the collection.

Now, Iā€™m uncertain if itā€™s my lack of PHP knowledge, but this only adds the new item to a copy of the collection. When I get the collection again, just after adding an item, the origin collection is not updated. Itā€™s like it only updates the ā€˜copyā€™.

So, is it even possible to extend collections dynamically in a template by calling functions and render those additions later?

The alternative workaround is to not try to do this dynamically in the templates, but already statically add those additional titles to the collection in my collection-name.php collection file. But that makes it a bit more difficult to maintain.

The collection itself cannot be modified. You can only store the modified copy in a new variable.

Or you create for example a page model and store the resulting collection in a static property that you can use everywhere where the page type is used.

Thank you for the prompt answer. Then I probably take my supposed workaround approach. I guess my idea of adding values top down in the template can anyway not work, assuming that I then again want to render the result add the top of the template, so Iā€™m anyway damned to create the whole collection in advance. :slight_smile:

Thank you.