首页 > 解决方案 > 在 drupal 8 的标题区域添加自定义类

问题描述

我想在我的 drupal 模板的标题区域中添加自定义类,但它不起作用。

<!-- BEGIN OUTPUT from 'themes/marinenat/templates/layout/page.html.twig' -->
<div class="layout-container">

  <header role="banner">
    

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'region' -->
<!-- FILE NAME SUGGESTIONS:
   x region--header.html.twig
   * region.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/marinenat/templates/layout/region--header.html.twig' -->
<div class="nav">

我想在“nav”类di region--header之后添加这个类。

任何人都可以帮助我

标签: classdrupalhookregion

解决方案


您已经在输出中拥有了所需的一切。

多条路通罗马

如果themes/marineat您是基本主题,只需复制themes/marinenat/templates/layout/region--header.html.twig到子主题的themes/MYSUBTHEME/templates目录并编辑此文件。刷新缓存。完毕。

如果themes/marinenat您是自定义子主题,只需编辑建议的模板文件/themes/marinenat/templates/layout/region--header.html.twig/并在那里添加您的类。刷新缓存。完毕。

最后但并非最不重要的一点是,您还可以从MYSUBTHEME.theme文件或任何MYMODULE.module文件的预处理函数将类添加到区域。

/**
 * Implements template_preprocess_region().
 */
function MYTHEME/MYMODULE_preprocess_region(&$variables) {

  if (isset($variables['region']) && $variables['region'] == 'header') {
    $variables['attributes']['class'][] = 'MYCLASS';
  }
}

如何将字符串从 PHP 传递到 Twig

/**
 * Implements template_preprocess_region().
 */
function MYTHEME/MYMODULE_preprocess_region(&$variables) {

  $variables['foo'] = FALSE;

  if (isset($variables['region']) && $variables['region'] == 'header') {       

    // Get the current node.
    $node = \Drupal::routeMatch()->getParameter('node');

    if ($node instanceof \Drupal\node\NodeInterface) {

      // Get the node type.
      $node_type = $node->bundle();

      // Do what ever else you need to do to retrieve your class dynamically.
      $variables['foo'] = $node_type;
    }
  }
}

然后在你的region--header.html.twigTwig 文件中它是:

{% if foo %}
  <div class="nav {{ foo }}">
    {{ content }}
  </div>
{% endif %}

推荐阅读