I want to create a body class for the published state of a node. I found some suggestions below for Drupal 7, but this code is not working for my Drupal 8 theme.

Add class based on published state

How can I acheive this?


You can fetch the node using routeMatch and add the class like this:

function THEME_NAME_preprocess_html(&$variables) {
  $routeMatch = \Drupal::routeMatch();
  $node = $routeMatch->getParameter('node');
  if (isset($node) && $routeMatch->getRouteName() == 'entity.node.canonical') {
    if ($node->isPublished()) {
      $variables['attributes']['class'][] = 'class-name-published';
    else {
      $variables['attributes']['class'][] = 'class-name-unpublished';

This only adds the body class if you're on the entity.node.canonical route, to make sure that we always get a node object from the route parameter.

| improve this answer | |
  • 2
    This is called on any route, so you might want to check either the route name or whether the route parameter is really a node object. There are routes in core which don't provide a node object by that parameter name. – 4k4 Sep 10 '19 at 16:47
  • 2
    See for example drupal.org/project/bootstrap_mint/issues/2918947 – 4k4 Sep 10 '19 at 16:53
  • Thanks for the feedback. Added a check to see if we're on the correct route. – user72672 Sep 10 '19 at 17:23
  • Works a treat. Thank you all. – MrPaulDriver Sep 11 '19 at 7:13

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.