I’m trying to write a pastebin plugin for Grav. My ideal structure is as follows:
- All paste data is stored under
data/pastebin/*.json
. Easy enough. - 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. - 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);
}