Drupal 8 hook_theme_suggestions_HOOK_alter() 未使用

ste*_*luk 1 drupal drupal-theming drupal-8

我使用hook_theme_suggestions_HOOK_alter()根据内容类型为 page.html.twig 添加主题挂钩建议:

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

现在我的树枝调试模式发现了这一点:

    <!-- 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
   -->
Run Code Online (Sandbox Code Playgroud)

但是,当我创建一个名为 的文件时page--node--case.html.twig,它没有被渲染。相反,page.html.twig正在被使用。

有人知道发生了什么事吗?

ste*_*luk 6

我发现出了什么问题。

显然,在定义新建议时,Drupal 需要下划线而不是破折号。然后Drupal将这些下划线转换为破折号,这样实际的文件名仍然是page--node--case.html.twig

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

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

文档: https: //www.drupal.org/node/2186401