David Lohmeyer's Blog

Adding the node class to a body HTML tag in Drupal 8

Doing some hacking at DrupalCon New Orleans and my use case is to add a node-* class to the body HTML element in Drupal 8. With the preprocess hook in D8 it looks like there is access to different variables than previously. To get the node id one has to look at the cache tags. Here's how I did it:

In mytheme.theme:

function mytheme_preprocess_html(&$variables) {
  // Add node id to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

In your html.html.twig include this:

<body{{ attributes }}>

</body>

 

Related Posts