11

drupal_get_title() has been removed from Drupal 8. How I can get the page title in Drupal 8?

20

If you check the change records you should find the following: drupal_set_title() and drupal_get_title() were removed.

You'll have to read the change notice for all of the info, but here is a starting point:

drupal_get_title()

As titles on routes now can be set on various ways (see above), drupal_get_title() has been removed. In its place you should call the title_resolver service.

Drupal 7

<?php
  $title = drupal_get_title();
?>

Drupal 8

<?php
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }
?>
  • 1
    The accepted response is out of date: see elsewhere in this thread for CurrentRouteMatch. – J-P Jul 19 '17 at 15:45
7

As per batch_test.module (D8.4) the following should work just fine:

$request     = \Drupal::request();
$route_match = \Drupal::routeMatch();
$title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

For more info see public function TitleResolver::getTitle.

0

Note

The accepted response for this question is out of date: See Request parameters, route name, and route object should be accessed via RouteMatch.

You should use the current_route_match service to retrieve the current route, and then read or modify its parameters. This wraps any Symfony etc. magic.

In procedural code, you would use code similar to the following one.

$route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
$title = $route->getDefault('_title');

In object-oriented code, you should use dependency injection and inject the service.

  • What to do if there is no $route->getDefault('_title'); but only a $route->getDefault('_title_callback');? – leymannx Nov 14 '17 at 10:38
  • For example on example.com/user/1 – leymannx Nov 14 '17 at 10:52
  • 1
    This bypasses the TitleResolver so doesn't handle all situations. api.drupal.org/api/drupal/… – imclean May 3 at 4:06
  • Using this solution will get the untranslated title. – Saud Alfadhli yesterday
-3

Drupal 8

$request = \Drupal::request();
  // Assuming the Request is $request.
  if ($request->attributes->has('_title')) {
    return $request->attributes->get('_title');
  }
  • I didn't mark this response down, but it looks like the ->get('_MAGIC') method is unfortunately deprecated and mostly removed from D8: drupal.org/node/2124749 – J-P Jul 19 '17 at 15:28

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.