Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

Access parent page property recursively

Solved by Kubenexion View solution

Started by Kubenexion 9 years ago · 2 replies · 1611 views
9 years ago

Hi there!

I am currently creating a custom theme and I add a color property on my pages.

I want, in templates, get the color property for the page and if not defined the parent page color property and if not defined the grand-parent page color property...

Is there a function to get a property recursively?

I tried to make one:

PHP
    public function onTwigInitialized()
    {
        $this->grav['twig']->twig()->addFunction(
            new \Twig_SimpleFunction('get_color', [$this, 'getColor'])
        );
    }

    function getColor($page)
    {
        do {
            $color = $page->header->color;
            $page = $page->parent;
        } while(!$color && $page);

        return $color;
    }

It defines a custom twig function get_color with a page parameter, but $page->header is a protected field...

9 years ago Solution

After reading the API and dumping some vars I found a solution:

PHP
    public function onTwigInitialized()
    {
        $this->grav['twig']->twig()->addFunction(
            new \Twig_SimpleFunction('recursive_header_var', [$this, 'getRecursiveHeaderVar'])
        );
    }

    function getRecursiveHeaderVar($varName)
    {
        $page = $this->grav["page"];
        do {
            $value = property_exists($page->header(), $varName) ? $page->header()->$varName : null;
            $page = $page->parent();
        } while ($value === null && $page->header());

        return $value;
    }

Now I can do {{ recursive_header_var('color') }} and get the color variable in the current page header or in the parent if not defined 😀

👍 3
9 years ago

Nice solution, thanks for sharing.

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by MarkP, 2 weeks ago
3 191 2 weeks ago
Themes & Styling · by TomW, 2 weeks ago
0 110 2 weeks ago
Themes & Styling · by themetman, 3 weeks ago
1 205 3 weeks ago
Themes & Styling · by AH, 1 month ago
1 323 3 weeks ago
Themes & Styling · by Bruno, 4 years ago
6 1522 3 weeks ago