Jason Thompson
Jason Thompson

Reputation: 21

Drupal 8 - adding body class based on taxonomy term or other

Building a site in Drupal 8, using classy subtheme. Run into a puzzling theming issue - adding body class to html.html.twig based on a taxonomy term on that node.

Themers use this to customize page display, in my case using it to define a few sections of my site so I can change color and format.

I have tried some preprocess functions I saw on google but to no result.

Has anyone else run into and solved this issue?

Upvotes: 2

Views: 2328

Answers (2)

Guicara
Guicara

Reputation: 1698

With the answer of Frank Drebin I get a PHP fatal error (Unsupported operand types) with the "+=" operand. If you want to add the node ID and node type to your body class, you can use this code for example:

// 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;

Upvotes: 1

Frank Drebin
Frank Drebin

Reputation: 1083

Use this to get all fields of the node and check for whatever you need:

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

In your .theme file you can use the html preprocess hook:

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;
}

And then in your html twig template add the attributes to the body element:

<body{{ attributes }}>

Hope this helps.

Upvotes: 1

Related Questions