Skip to content
Grav 2.0 is officially stable. Read the announcement →
Themes & Styling

Access parent page property recursively

Solved by Kubenexion View solution

Started by Kubenexion 9 years ago · 2 replies · 1218 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 Sebadamus, 7 days ago
5 148 15 hours ago
Themes & Styling · by martynfoster735, 1 week ago
1 193 1 week ago
Themes & Styling · by Justin Young, 3 weeks ago
1 241 3 weeks ago
Themes & Styling · by Slebeig, 1 month ago
4 376 1 month ago
Themes & Styling · by Pedro M, 3 months ago
4 745 3 months ago