Drupal - How do I set the page title?

As reported in drupal_set_title() and drupal_get_title() were removed that function is deprecated in Drupal 8.

For a dynamic title set from a controller, the code the change record suggests is the following one.

mymodule.test:
  path: '/mymodule/test'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Test::getContent'
    _title_callback: '\Drupal\mymodule\Controller\Test::getTitle'

The controller code is the following one.

class Test {

  /**
   * Returns a page title.
   */
  public function getTitle() {
    return  'Foo: ' . \Drupal::config()->get('system.site')->get('name');
  }

  /**
   * Returns a page render array.
   */
  public function getContent() {
    $build = array();
    $build['#markup'] = 'Hello Drupal';
    return $build;
  }

}

Alternatively, as the same change record suggests, you could use the #title property in a render array. This should be generally avoided, since the title for the page when fully rendered could be different from the title in other contexts (like in the breadcrumbs).

class Test {

  /**
   * Renders a page with a title.
   *
   * @return array
   *   A render array as expected by drupal_render()
   */
   public function getContentWithTitle() {
     $build = array();
     $build['#markup'] = 'Hello Drupal';
     $build['#title'] = 'Foo: ' . Drupal::config()->get('system.site')->get('name');
     return $build;
   }

}

drupal_set_title() in Drupal 8

$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', 'New Title');
}

drupal_get_title() in Drupal 8

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

That function was removed from Drupal 8.
Change record: drupal_set_title() and drupal_get_title() were removed.

You could now set the title when defining the routes in modulename.routing.yml. Example of how it could be done, is shown the change record link above.

Tags:

8