Set the page title programmatically in D8

Submitted by editor on Thu, 12/10/2015 - 18:24
Question

How to set the page title programmatically in Drupal 8 ?

Example:

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

 

For a form, just set $form['#title'].

Example : $form['#title'] = "The title";

Tags

Comments

Thomas M. (not verified)

Wed, 07/27/2016 - 14:11

works in Drupal 8.1.7 only with nodes created by custom module/plugin, not for drupal content types like Article or Basic Page

working:

class CustomController extends ControllerBase implements ContainerInjectionInterface

      public function getBlockContent() {

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

      }

}

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.