Cookie Settings

This site uses cookies that need consent. Learn more

Skip to content

Statamic: Check whether a navigation exists

In some projects, it is desirable or necessary for certain navigation areas to remain optional. Especially when the navigation is maintained by the customer, it can happen that a navigation is accidentally deleted or has not yet been set up.

In such cases, it is important that the page does not react with an error 500, but instead remains clean and stable - even without navigation.

In this article, I will show you two approaches for checking whether a navigation exists in Statamic and using this information sensibly in the template.

Statamic: Check if a navigation exists.

Scenario

  • Navigation is optional and is managed by the customer.

  • The aim is to prevent the absence of navigation from leading to an error.

  • The aim is to achieve flexible, error-tolerant output in the front end.

Variant 1: Own tag for checking the navigation

With a user-defined tag, you can specifically check whether a certain navigation is available. This allows you to specifically control the output in the template.

Example: app/Tags/NavExists.php

<?php

namespace App\Tags;

use Statamic\Eloquent\Structures\NavModel;
use Statamic\Tags\Tags;

class NavExists extends Tags
{
    /**
     * Check if a navigation is configured.
     */
    public function nav(): bool
    {
        return NavModel::query()
            ->where('handle', $this->params['handle'])
            ->get()
            ?->isNotEmpty() ?? false;
    }
}

Use in the template:

{{ if nav_exists:nav handle="header" }}
  
{{ /if }}

Advantages:

  • Full control over the display.

  • No internal changes to the standard behaviour necessary.

Note: You must include the check in each template yourself.

Variant 2: Overwrite the standard nav tag

Alternatively, you can overwrite the existing nav tag in Statamic and add the check directly there.
If the desired navigation does not exist, an empty navigation tree is simply returned.

Example: app/Tags/Nav.php

<?php

namespace App\Tags;

use Statamic\Eloquent\Structures\NavModel;
use Statamic\Tags\Nav as BaseNav;

class Nav extends BaseNav
{
    public function index()
    {
        $handle = $this->params->get('handle', 'collection::pages');

        $exists = NavModel::query()
            ->where('handle', $handle)
            ->get()
            ?->isNotEmpty() ?? false;

        if (! $exists) {
            return ['items' => []];
        }

        return $this->structure($handle);
    }
}

Advantage: Templates remain unchanged

Advantages:

  • No additional effort in the templates.

  • Existing calls to the nav tag work as usual.

  • Errors due to missing navigation are automatically intercepted.