4

I am trying to print out a few links on a custom page template. I would like to use the title and url from each route.

I am trying to print out the title from the route.

I know I can get the url from:

$url = Url::fromRoute('route.name');

and I know I can get the current page title from

$request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route); }

but I am not sure how to request the title from a specific/ different route.

Thanks in advance.

2

The only way to get the page title of any URL/route would be to actually request the page and see what the title is. The reason is that any module or the theme could alter the title from what it normally would be, like fx metatags module.

0

There are many reasons why this would be a bad idea, but if you're OK with ignoring the current request context or any dynamic arguments, there is a default title stored in the route object:

$title = $route->getDefault('_title');

(this is more or less the fallback functionality of the TitleResolver)

This works, for instance, for a plain text Views page title.

0

Expanding on @ahebrank's answer, if you have the route name 'my.route.name', but not the route object itself (and taking into account the caveat's mentioned by @ahebrank's) here's how you can do it:

    $route_provider = \Drupal::service('router.route_provider');
    $route = $route_provider->getRouteByName('my.route.name');
    $title = $oRoute->getDefault('_title');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.