Drupal - How do I add a node ID as class to the <body> tag?

In mytheme.theme file: add the below code.

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

This will add "node-{{nid}}" class in body tag.

Another Option

You can try Node Class module as well.

Node Class is a simple module that allows users to add custom CSS classes to any node through the node/add interface.

Tags:

Theming

8