Skip to content

Instantly share code, notes, and snippets.

@MatthieuScarset
Last active November 25, 2022 14:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthieuScarset/d96dff54ac31496e3bf725c7459a9ddf to your computer and use it in GitHub Desktop.
Save MatthieuScarset/d96dff54ac31496e3bf725c7459a9ddf to your computer and use it in GitHub Desktop.
Get the page title from a Url in Drupal 8+
<?php
/**
* @file
* Contains a custom function to get the title from a Url.
*/
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\Request;
/**
* Get the title from a Url.
*
* @param \Drupal\Core\Url $url
* A given URL.
*
* @return string|null
* The resolved title or nothing.
*
* @example Get the title for current page.
* $current_url = Url::fromRoute('<current>');
* $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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment