How to get object of specific page in Grav plugin

290 Views Asked by At

I've tried a lot of ways, but without success

For example

use Grav\Common\Page\Pages;

public function onPagesInitialized()
{
    $pages = $this->grav['pages'];
    print_r($pages->get('/about'));
    // or
    print_r($pages->find('/about', true));
}

returns nothing

The plugin of flex objects is enabled


EDITED

Adding the function onPluginsInitialized() with enabling onPagesInitialized() also doesn't help:

public function onPluginsInitialized(): void
{
    $this->enable([
        'onPagesInitialized' => ['onPagesInitialized', 0],
    ]);
}
1

There are 1 best solutions below

0
passerby On BEST ANSWER

The following is a sample of how one can get a specific page object.

When using the following folder structure: (from Blog skeleton)

user/pages
└── 01.blog
    ├── blog.md
    ├── ...
    ├── hero-classes
    │   ├── item.md
    │   └── unsplash-overcast-mountains.jpg
    ├── london-at-night
    │   ├── item.md
    │   ├── unsplash-london-night.jpg
    │   └── unsplash-xbrunel-johnson.jpg
    └── ...

Assuming event 'onPagesInitialized' has been subscribed to, the following code correctly returns the sought pages:

public function onPagesInitialized(Event $event) {
    /** @var Pages */
    $pages = $event['pages']; // or $this->grav['pages'];

    $p1 = $pages->find('/blog');
    $p2 = $pages->find('/blog/london-at-night');
    $p3 = $pages->find('/blog/hero-classes');
}

Note: When the request is made by plugin Admin, pages will not be initialized. One needs to call $this->grav['admin']->enablePages(); first.

public function onPagesInitialized(Event $event) {
    $this->grav['admin']->enablePages();

    /** @var Pages */
    $pages = $event['pages']; // or $this->grav['pages'];

    $p1 = $pages->find('/blog');
    $p2 = $pages->find('/blog/london-at-night');
    $p3 = $pages->find('/blog/hero-classes');
}