Search code examples
drupaldrupal-themingdrupal-8

Drupal 8 hook_theme_suggestions_HOOK_alter() not being used


I'm using hook_theme_suggestions_HOOK_alter() to add theme hook suggestions for page.html.twig based on the content type:

function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $node = \Drupal::request()->attributes->get('node');
  $suggestions[] = 'page--node--' . $node->getType();
}

Now my twig debug mode picks this up:

    <!-- FILE NAME SUGGESTIONS:
   * page--node--case.html.twig (new suggestion based on content type 'case')
   * page--node--3.html.twig
   * page--node--%.html.twig
   * page--node.html.twig
   x page.html.twig
   -->

However, when I make a file called page--node--case.html.twig, it is not being rendered. Instead, page.html.twig is being used.

Anyone know what's going on?


Solution

  • I found out what was going wrong.

    Apparently, when defining new suggestions, Drupal needs underscores instead of dashes. Then Drupal converts these underscores into dashes so that the actual file name will still be page--node--case.html.twig

    So: $suggestions [] = 'page--node--'.$node->gettype();

    Should be: $suggestions [] = 'page__node__'.$node->gettype();

    Documentation: https://www.drupal.org/node/2186401