I give up.. Tried to figure out, but prev() and next() are already taken because of already implemented \Iterator and \ArrayCollection both on flex and non-flex pages collections.
Also in Twig neither colleection.prev() nor collection.next() work. prev() always returns false or an array which only contains a slug of the page (['slug' => 'page-slug']) and next() always returns null.
Although both prev() and next() moves the pointer and then current() gives the correct page, but there's a problem - no way to set a pointer to a current page
I really don't have time to figure out why the implementation of prev() and next() is as it is, but IMO this really requires a solution, so that we could get items we expect and not in reverse :(
OK.. Is there any chance such method would be approved in system/src/Grav/Common/Page/Collection.php?
/**
* Set current page.
*/
public function setCurrent(string $path): void
{
reset($this->items);
while (key($this->items) !== $path && key($this->items) !== null) {
next($this->items);
}
}
Then in Twig I could do this:
{% set collection = page.parent.collection({items: '@self.children', filter: {published: true, routable: true}}) %}
{% set isFirst = collection.isFirst(page.path) %}
{% set isLast = collection.isLast(page.path) %}
<section>
{% if not isFirst %}
{% do collection.setCurrent(page.path) or collection.prev %}
<a href="{{ collection.current.url }}">Previous page</a>
{% endif %}
{% if not isLast %}
{% do collection.setCurrent(page.path) or collection.next %}
<a href="{{ collection.current.url }}">Next page</a>
{% endif %}
</section>
Although I don't get why prev() and next() would have completely different implementations 🤔 I think this also should be fixed in Grav 2.0 - all these methods should behave as in PHP. At least that's what I would expect. At the very least, that prev/next would return same type values