Use the request_stack service in Drupal to get information about the current request. This can be used to find the current path and route like this.
// Get the current path.
$path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
// $path now contains "/some-page-path".
// Get the current route.
$requestRouteName = \Drupal::requestStack()->getCurrentRequest()->attributes->get('_route');
// $requestRouteName now contains "entity.node.canonical".
It is generally better to get the route name as this will catch more paths and will be less likely to change.
Add new comment