2

I'd like to add a single taxonomy term into the body tag as a class in drupal 8 - so I page styles can be controlled easily. I have tried (path and ID as class in body How can I dynamically add URL or taxonomy to body class and https://www.drupal.org/node/2634364) which only get me part way there, taxonomy term would provide a future proofed solution.

4

i found a solution which worked perfectly for me. Add this in your .theme file and replace mytheme_preprocess_html by your theme name and field_section by name of your taxonomy field.

[https://gist.github.com/awasson/d8ef8d7c1b64b2ccb8a0][1]

<?php

    /**
     * Prepares variables for the html.html.twig template.
     */

    use Drupal\taxonomy\Entity\Term;
    use Drupal\Component\Utility\Html;

    function mytheme_preprocess_html(&$variables) {

      if ($node = \Drupal::routeMatch()->getParameter('node')) {

        /**
         * Get the term id from the 'field_section' taxonomy field.
         * If greater than zero, load the term and acquire the name value 
         * as a css safe value.
        */
        if($node->hasField('field_section')) {
          $tid = $node->get('field_section')->target_id;
          if($tid > 0) {
            $term_object = Term::load($tid);
            $variables['attributes']['class'][] = 'terms--' . Html::getClass($term_object->get('name')->value);
          }
        }

        /**
         * Get the node id from the node object.
         * If greater than zero, add the node id to body classes  
        */
        $nid = $node->get('nid')->value;
        if($nid > 0) {
          $variables['attributes']['class'][] = 'page--node-' . $nid;
        }
      }

    }

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.