Access parent page property recursively

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:

    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…

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

    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 :grinning:

3 Likes

Nice solution, thanks for sharing.