How to add a theme preprocess function for published state? 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(&amp;$variables) {
  $routeMatch = \Drupal::routeMatch();
  $node = $routeMatch-&gt;getParameter('node');
  if (isset($node) &amp;&amp; $routeMatch-&gt;getRouteName() == 'entity.node.canonical') {
    if ($node-&gt;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.