If I have a Url
object, or even a simple string representation of path such as /node/2
, how can I get the full Route
object?
1 Answer
You can retrieve this information from the Symfony router. This can be accessed in Drupal through the router.no_access_checks
service.
If you have a simple path (note that the path has a leading slash):
$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');
If you have a Url
object:
$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());
This will return an array that includes the route object, as well as other useful information such as the route name and route parameters, the controller, the title callback and even the entity object represented by the URL.
-
To get just the route string:
drush eval "echo \Drupal::service('router.no_access_checks')->match('/some/path')['_route'];
– mbomb007Commented Jun 28 at 16:15