Drupal - How can I get the page title?

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);
  }
?>

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.

Tags:

8