Hook to change page title

12,495

Solution 1

In your template.theme file add the preprocessor and then override page-title.html.twig in your template folder by printing the variable, like below:

function theme_preprocess_page_title(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  $nid = $node->id();
  if($nid == '14') {
    $variables['subtitle'] = 'Subheading';
  }
}

then {{ subtitle }}

Solution 2

Here's the method to preprocess your page :

function yourthemename_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    $variables['title'] = $node->getTitle();
  }
}

and in your template page.html.twig

{{title}}

Solution 3

There are a couple of solutions to change the page title

On template

/**
 * Implements hook_preprocess_HOOK().
 */
     function MYMODULE_preprocess_page_title(&$variables) {

      if ($YOUR_LOGIC == TRUE) {
          $variables['title'] = 'New Title';
     }
     }

On the node view page

/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
      if ($YOUR_LOGIC == TRUE) {
  $build['#title'] = $entity->get('field_display_name')->getString();
  }
}

for a sample if you want to change user title

function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if ($entity->getEntityTypeId() == 'user') {  
  $build['#title'] = $entity->get('field_first_name')->getString();
  }
}

On Controller or hook_form_alter

if ($YOUR_LOGIC == TRUE) {
$request = \Drupal::request();
if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
  $route->setDefault('_title', 'New Title');
 }
}
Share:
12,495
wonder_dev22
Author by

wonder_dev22

Updated on June 04, 2022

Comments

  • wonder_dev22
    wonder_dev22 almost 2 years

    I want to programmatically alter a page title in Drupal 8 so that it will be hard-coded in the theme file.

    I'm attempting to use a hook function to preprocess_page_title, but it seems to not understand what page to change the title on.

    Here's what I have so far:

    function test_preprocess_page_title(&$variables) {
      if (arg(0) == 'node/12') {
        $variables['title'] = 'New Title';
      }
    }
    

    I figured the only way to make this change on one specific page is to set the node argument. Has any one figured out a way to override page title on Drupal?

  • user151841
    user151841 over 4 years
    This is a great answer. Thanks!