Refactor routing and page classes to be more flexible

This commit is contained in:
Dale Davies
2022-07-14 15:59:11 +01:00
parent 7af5e03784
commit 4b5d51ee52
3 changed files with 9 additions and 10 deletions

View File

@@ -23,7 +23,7 @@ class Main {
$this->router = new RouteList;
// Set up the routes that Jump expects.
$this->router->addRoute('/tag/<param>', [
$this->router->addRoute('/tag/<tag>', [
'class' => 'Jump\Pages\TagPage'
]);
}
@@ -49,12 +49,11 @@ class Main {
$matchedroute = $this->router->match($this->request);
// If we do not have a matched route then just serve up the home page.
$pageclass = $matchedroute['class'] ?? 'Jump\Pages\HomePage';
$param = $matchedroute['param'] ?? null;
$outputclass = $matchedroute['class'] ?? 'Jump\Pages\HomePage';
// Instantiate the correct class to build the requested page, get the
// content and return it.
$page = new $pageclass($this->config, $this->cache, $this->session, $param ?? null);
$page = new $outputclass($this->config, $this->cache, $this->session, $matchedroute ?? null);
return $page->get_output();
}

View File

@@ -18,7 +18,7 @@ abstract class AbstractPage {
protected \Jump\Config $config,
protected \Jump\Cache $cache,
protected \Nette\Http\Session $session,
protected ?string $param = null
protected ?array $routeparams
){
$this->hastags = false;
$this->mustache = new \Mustache_Engine([

View File

@@ -8,13 +8,13 @@ class TagPage extends AbstractPage {
protected function render_header(): string {
$template = $this->mustache->loadTemplate('header');
$greeting = $this->param;
$title = 'Tag: '.$this->param;
$this->tagname = $this->routeparams['tag'];
$title = 'Tag: '.$this->tagname;
$csrfsection = $this->session->getSection('csrf');
$unsplashdata = $this->cache->load('unsplash');
$templatecontext = [
'csrftoken' => $csrfsection->get('token'),
'greeting' => $greeting,
'greeting' => $this->tagname,
'noindex' => $this->config->parse_bool($this->config->get('noindex')),
'title' => $title,
'owmapikey' => !!$this->config->get('owmapikey', false),
@@ -34,11 +34,11 @@ class TagPage extends AbstractPage {
}
protected function render_content(): string {
$cachekey = isset($this->param) ? 'tag:'.$this->param : null;
$cachekey = isset($this->tagname) ? 'tag:'.$this->tagname : null;
return $this->cache->load(cachename: 'templates/sites', key: $cachekey, callback: function() {
$sites = new \Jump\Sites(config: $this->config, cache: $this->cache);
try {
$taggedsites = $sites->get_sites_by_tag($this->param);
$taggedsites = $sites->get_sites_by_tag($this->tagname);
}
catch (TagNotFoundException) {
(new ErrorPage($this->cache, $this->config, 404, 'There are no sites with this tag.'))->init();