Adding node-id CSS class in Drupal 8

Let say that we’d like to add a node-id-1 CSS class name to the HTML tag. (Ideally, the front-end should not depend on node ids, however, sometimes it’s the best approach)

Add a pre-processor to the theme file. Note that the preprocess function doesn’t know what the current node is, therefore you need to call \Drupal::routeMatch() function which will return the currently active route match object. This allows you to run the getParameter() function and to get the current node.

Once you have the current node, get it’s id by calling the id() function. Save it in the render array.

function THEME_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if($node){
    $variables['node_id'] = 'node-id-' . $node->id();
  }
}

Now you need to add the node_id variable to the HTML tag.

{%
  set body_classes = [
    node_id|clean_class,
  ]
%}

Leave a comment

Your email address will not be published. Required fields are marked *