Creating a Page in the Plugin

I’m trying to write a pastebin plugin for Grav. My ideal structure is as follows:

  1. All paste data is stored under data/pastebin/*.json. Easy enough.
  2. The pastebin is located at /pastebin. Going to this URL will display a table of all pastes that have been made so far. This part works.
  3. A paste can be viewed at /pastebin/view/paste_id_#.

Number three is where I’ve ran into some difficulty. Obviously, there won’t be a subpage for each paste. Instead, I’ve set the plugin to grab any page that starts with /pastebin/view/, and then I’ll use the plugin to separate and pull the data from the remainder of the URL. Using the dump() command, I’ve established that I can get the plugin to recognize that I have browsed to the desired path, and that no page exists.

I’ve tried using the Login plugin as an example on how to handle a missing page, but no matter what I do I just get an Error not found page. My code so far is below, I’m hoping someone could point out where I’ve gone wrong.

— php
public function onPluginsInitialized()
{
// Don’t proceed if we a re in the admin plugin
if ($this->isAdmin()) {
return;
}

// Enable the main event we are interested in
$this->enable([
    'onGetPageTemplates' => ['onGetPageTemplates', 0],
    'onTwigTemplatePaths' => ['onTwigTemplatePaths', -10],
]);

// route needs to be set as a plugin variable in the future!
$this->route = '/pastebin/view/';
$this->path  = $this->grav['uri']->path();

// the path viewed is a paste initialize the page
if( strpos($this->path, $this->route) !== false ) {
    $this->enable([
        'onPageInitialized' => ['onPageInitialized', 0]
    ]);
}

}

public function onPageInitialized()
{
/** @var Pages $pages */
$pages = $this->grav[‘pages’];
// $page = $pages->dispatch();
$page = $pages->dispatch($this->path);

if (!$page) {
    // Only add page if it hasn't already been defined.
    $page = new Page;
    $page->init(new \SplFileInfo(__DIR__ . "/pages/paste.md"));
    $page->slug(basename($this->path));

    $pages->addPage($page, $this->path);
}

}

When I dump the $page variable, it does show the title and content found in __DIR__ . pages/paste.md. So it’s just not displaying properly for some reason.

While realising I’m on thin ice here, I doubt this will work. Why don’t you insert the pastebin data as page content using the Page Inject Plugin ?

@bleutzinn: I actually got it to work earlier this morning. I chose to do it this way since both Login and Simple Search operate using this method.

— php
if (!$page) {
// Only add page if it hasn’t already been defined.
$page = new Page;
$page->init(new \SplFileInfo(DIR . “/pages/paste.md”));
// $page->slug(basename($this->route));

unset($this->grav['page']);
$this->grav['page'] = $page;

// set a page variable to store the paste id
// that the user is looking for
$this->grav['page']->paste = $this->GetPaste()

}