1

I know I can customize the template by overriding page-title.html.twig but I'm looking for a way to have more than one title template. in my case, the suggested name form my path is page__manage__customer_list So I tried to override it with page--manage--customer-list-title.html.twig. how is that possible to override the title template?

to make the question more generalize and could be useful for other guys that looking for similar circumstances this could be helpful.

How can I override the title template based on content type or route?

2

You can add new templates to already existing using hook_theme_suggestions_HOOK_alter

Example of adding a content type:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
}

Then use page-title--content-type.html.twig


You could use $node->id(); if content type is too broad.

2

Many thanks for @No Sssweat give a clue to me. her solution works for content types only. but for Taxonomy page and General pages ( custom pages you've created by custom route like me) the following snippet will work charmingly:

on YOURTHEMENAME.theme file

use \Drupal\taxonomy\Entity\Term;
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function YOURTHEMENAME_theme_suggestions_page_title_alter(array &$suggestions, array $variables) {

  $path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  $suggestions = theme_get_suggestions($path_args, 'page_title');

  if ($tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $vid = $term->vid->getValue();
    $suggestions[] = 'page_title__taxonomy__vocabulary__' . $vid[0]['target_id'];
  }

  elseif ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page_title__' . $content_type;
  }
 // ksm($suggestions);
}

then it works for all pages.

page-title--CONTENT_TYPE_MACHINE_NAME.html.twig (sample for article content type : page-title--article.html.twig

page_title__taxonomy__vocabulary__VOCABULARY_MACHINE_NAME.html.twig ( sample for tags vocabulary is : page_title__taxonomy__vocabulary__tags.html.twig

Ref : hook_theme_suggestions_HOOK_alter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.