Site visit in controller alternative?


#1

As far as I know we can’t use site()->visit() in a controller. On my new site I would like to visit the error page in case something is not right with my pagination function (could be any function).

What I ended up with was a quite messy solution. While it works, maybe there is a more brilliant way? I’m aware of that I could move things to a route instead but then I would get extra code to maintain over there instead. I’m also not too fond of routing (:any)/(:any).

<?php
return function($site, $pages, $page) {
    $data = somePaginationFunction();

    if($data['pagination']->error) {
        $PageGenerator = new PageGenerator(kirby());
        $data = $PageGenerator->render(
            kirby()->roots()->site() . '/components/--error/component.php',
            $data,
            page('error')
        );
        echo $data;
        die;
    }
    return $data;
}

I also made a plugin that looks like this:

<?php
class PageGenerator extends Kirby\Component\Template {
    public function render($template, $data = [], $page = null) {
      $file = $template;
      $data = $this->data($page, $data);
  
      if(!file_exists($file)) {
        throw new Exception('The template could not be found');
      }
  
      $tplData = tpl::$data;
      tpl::$data = array_merge(tpl::$data, $data);
      $result = tpl::load($file, null);
      tpl::$data = $tplData;
  
      return $result;
    }
}

I’m don’t have high expectations that it’s possible to solve in a better way, but I thought I’ll give it a try here anyway.