getkirby / ideas

This is the backlog of ideas and feature requests from the last two years. Use our new feedback platform to post your new ideas or vote on existing ideas.
https://feedback.getkirby.com
20 stars 0 forks source link

`$page->topmostParent()` method #307

Open lukasbestle opened 5 years ago

lukasbestle commented 5 years ago

I often have the need to get the "topmost parent" of the current page like this:

home                -> home
photography         -> photography
photography/animals -> photography

Current implementation in a page method:

Kirby::plugin('my/plugin', [
    'pageMethods' => [
        'topmostParent' => function(): ?Page {
            if (isset($this->topmostParent)) {
                return $this->topmostParent;
            }

            // get the topmost parent
            $topmostParent = $this->parents()->last();

            // if there is no parent, the current page is already it
            if ($topmostParent === null) {
                $topmostParent = $this;
            }

            return $this->topmostParent = $topmostParent;
        }
    ]
]);

I think this could be a good fit for a core page method.

distantnative commented 5 years ago
return $this->topmostParent = $this->topmostParent ?? $this->parents()->last() ?? $this;

We could make it a one-liner 😄

lukasbestle commented 5 years ago

That‘s right, but is that desirable? I think it‘s a lot harder to read.