Get view router name

Get view router name

Sometimes, we have to get a view router name and there is a common case for it is use a code like this:

<?php

$route_name = \Drupal::routeMatch()->getRouteName();

But, if we already have a view object we can use this code to get the router name or router object:

<?php

use Drupal\Core\Routing\RouteObjectInterface;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_preprocess_views_view().
 */
function MODULENAME_preprocess_views_view(array &$variables): void {
  /** @var \Drupal\views\ViewExecutable $view */
  $view = $variables['view'];
  
  // The view router name.
  $view_router_name = $view->getRequest()->get(RouteObjectInterface::ROUTE_NAME);

  // The view router object.
  $view_router_object = $view->getRequest()->get(RouteObjectInterface::ROUTE_OBJECT);
}