Check if page exist?

Hi everybody,

I have a simple Plugin, a Kirbytag (sitemap:) which has two options:

  • when tag empty, list all children of the Site
  • when not empty, search after a page and list children of that

All is working fine, but when I enter in the Kirbytag a page that doesn’t exist, I kill my site. Is there any code I can check if that page exists to prevent crashing the whole site?

Maybe this code is not working very well? But as I know, it’s the only code where pages find, no matter on which menu level right?

$sitemap = $site->index()->find($tag->value)->children()->listed();

Here’s the whole Plugin

'sitemap' => [
    'attr' => [],
    'html' => function ($tag) {
      
      $page = page();
      $site = site();

      if ( empty($tag->value) ) {
        
        $sitemap = $site->children()->listed();
        
      } else {
        
        $sitemap = $site->index()->find($tag->value)->children()->listed();
        
      }

      if ( $sitemap->isNotEmpty() ) {
        
        $sitemap_code = '<ul>';
      
        foreach ( $sitemap AS $entry ) {
          
          $sitemap_code .= '<li><a href="' . $entry->url() . '">' . $entry->title() . '</a></li>';

        }
      
        $sitemap_code .= '</ul>';
        
      } else {
        
        $sitemap_code = '<div class="alert alert-danger">Leider wurde die angegebene Seite nicht gefunden oder diese besitzt keine Unterseiten</div>';
        
      }

      return $sitemap_code;

    }
  ],
if ($page = $site->index()->find($tag->value)) {
  $sitemap = $page->children()->listed();
}

You always have to check if an object exists.

So simple, thanks a lot :slight_smile:

Sorry for reopen, but is this a good way to handle it? As I see, it’s working? Bit is it best practice?

if ( $page = $site->index()->find($tag->value) ) {
  $sitemap = $page->children()->listed();
} else {
  $sitemap = $site->empty();
}

if ( $sitemap->isNotEmpty() ) {
  echo 'Pages found, success';
} else {
  echo 'No pages found ... error';
}

It’s cause I have a condition below where I check if the object is empty.

There is no $site->empty() method?

$sitemap = new Pages();
if ( $page = $site->index()->find($tag->value) ) {
  $sitemap = $page->children()->listed();
}

Or shorter:

$sitemap = ($page = $site->index()->find($tag->value)) ? $page->children()->listed() : new Pages();

I think this I was looking for. This creates a new empty Collection right?

Exactly.