How to alter the page title?

Components

One way to alter the page title is to use hook_preprocess_HOOK() and then set the new page title depending on the current route name.

function MY_MODULE_preprocess_page_title(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === 'entity.user.edit_form') {
    $variables['title'] = 'Edit My Account';
  }
}

This will only change the title in the Page title block. To actually change the <title> HTML tag you can use the following code snippet:

function MY_MODULE_preprocess_html(&$variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === 'entity.user.edit_form') {
    $variables['head_title']['title'] = t('Edit My Account')
  }
}

About the Author

Goran Nikolovski is a web and AI developer with over 10 years of expertise in PHP, Drupal, Python, JavaScript, React, and React Native. He founded this website and enjoys sharing his knowledge.