Drupal - How do I verify a route exists?

/* @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$route_provider->getRouteByName('abc.xyz');

RouteProviderInterface::getRouteByName() returns a \Symfony\Component\Routing\Route object if it exists, or throws an exception if it does not.

You can use RouteProviderInterface::getRoutesByNames() if you don't want an exception.

$exists = count($route_provider->getRoutesByNames(['abc.xyz'])) === 1;

To check route exist or not use below function:

function routeExists($name)
{
    // I assume that you have a link to the container in your twig extension class
    $router = $this->container->get('router');
    return (null === $router->getRouteCollection()->get($name)) ? false : true;
}

Tags:

Routes

8