【问题标题】:Drupal 8 - adding body class based on taxonomy term or otherDrupal 8 - 根据分类术语或其他添加身体类
【发布时间】:2016-10-06 07:41:04
【问题描述】:

使用经典的子主题在 Drupal 8 中构建网站。遇到一个令人费解的主题问题 - 根据该节点上的分类术语将 body 类添加到 html.html.twig。

Themers 使用它来自定义页面显示,在我的例子中使用它来定义我网站的几个部分,以便我可以更改颜色和格式。

我尝试了一些我在 google 上看到的预处理功能,但没有结果。

有其他人遇到并解决了这个问题吗?

【问题讨论】:

    标签: drupal themes preprocessor drupal-8


    【解决方案1】:

    Frank Drebin 的回答下,我得到一个带有“+=”操作数的 PHP 致命错误(不支持的操作数类型)。如果您想将节点 ID 和节点类型添加到您的 body 类中,您可以使用以下代码,例如:

    // Add the node ID and node type to the body class
    
    $body_classes = [];
    $nodeFields = \Drupal::service('current_route_match')->getParameter('node')->toArray();
    
    if (is_array($nodeFields) && count($nodeFields) > 0) {
        if (isset($nodeFields['nid'])) {
            $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
        }
        if (isset($nodeFields['type'])) {
            $body_classes[] = $nodeFields['type'][0]['target_id'];
        }
    }
    
    $variables['attributes']['class'] = $body_classes;
    

    【讨论】:

      【解决方案2】:

      使用它来获取节点的所有字段并检查您需要的任何内容:

      \Drupal::service('current_route_match')->getParameter('node')->toArray();
      

      在您的 .theme 文件中,您可以使用 html 预处理挂钩:

      function your_theme_preprocess_html(&$variables) {
        $body_classes = [];
        $nodeFields = \Drupal::service('current_route_match')->getParameter('node')->toArray();
      
        // if something, then set $body_classes to something.
      
        $variables['attributes']['class'] += $body_classes;
      }
      

      然后在您的 html 树枝模板中将属性添加到 body 元素:

      <body{{ attributes }}>
      

      希望这会有所帮助。

      【讨论】:

      • 我将该代码放在我的 .theme 文件中(我的主题名称在正确的位置)但是 html.html.twig 文件中已经有经典的正文类代码,当我应用您的代码时,我得到了一个白色的屏幕。此代码在树枝模板中:''
      • 我也不知道如何在这里评论我的代码突出显示:(
      • “” 所做的是将定义的“body_classes”添加到属性变量中已经存在的任何类中。所以理论上它也应该起作用。您可以尝试使用“var_dump”或“kint”进行调试(如果您启用了开发模块)。你也可以直接在 twig 模板中进行 var dump:twig.sensiolabs.org/doc/functions/dump.html 但是你必须在你的 services.yml 中启用 twig 调试
      • 通常(根据我对 Drupal 8 的经验)白屏与 php 内存耗尽有关,因此您也可以在预处理函数中仔细检查您的逻辑。也许你使用了一些永无止境的循环?查看 php/server 日志也​​可能有所帮助。
      猜你喜欢
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多