Do you want to know how to Drupal?

Let's Drupal

Routing

How to provide full access to route in Drupal?

Let's imagine we don't want to have any restrictions for our route. For this we can set _access requirement to TRUE.

your_module.route_name:
  path: '/your_path'
  defaults:
     _controller: 'Drupal\your_module\Controller\YourController::yourMethod'
  requirements:
    _access: 'TRUE'

 


How to get a route by URI in Drupal?

If you have a basic path we can get route using router.no_access_checks service. Keep in my you have to have a leading slash

$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');

In case you have URL object we can get route from it like this

$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());


How to check if the current page using admin theme in Drupal?

To check this we need to use router.admin_context service

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
   // Do something here.
}

We also can check a specific route

$route_provider = \Drupal::service('router.route_provider');
$route = $route_provider->getRouteByName('user.page');
if (\Drupal::service('router.admin_context')->isAdminRoute($route)) {
   // Do something here.
}