'); * $page_title = mymodule_get_title_from_url($current_url); * * @example Get the title from a given path. * $path = '/my-custom-page-alias'; * $uri = 'internal:' . $path; * $url = Url::fromUri($uri); * $page_title = mymodule_get_title_from_url($url); * * @example Get the title from an entity. * $url = $entity->toUrl('canonical'); * $page_title = mymodule_get_title_from_url($url); * * @example Get the title from a current node page. * $node = \Drupal::routeMatch()->getParameter('node'); * $url = $node->toUrl('canonical'); * $page_title = mymodule_get_title_from_url($url); */ function mymodule_get_title_from_url(Url $url) { $router = \Drupal::service('router'); $title_resolver = \Drupal::service('title_resolver'); $route_match = $router->match($url->toString()); $route = $route_match['_route_object'] ?? NULL; if ($route) { try { $path = $url->setAbsolute(TRUE)->toString(); $request = Request::create($path); $attributes = $router->matchRequest($request); $request->attributes->add($attributes); return $title_resolver->getTitle($request, $route); } catch (\Exception $e) { \Drupal::logger('mymodule')->error($e->getMessage()); } } return NULL; }