How to add the entity type id to the body tag classes in Drupal 8

Submitted by Charles on Thu, 08/22/2019 - 17:20

This snippet adds the entity type id to the html body tag classes when on the canonical entity page.

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function yourtheme_preprocess_html(&$variables) {
  // If this is the canonical entity route, add the entity type id to the body
  // tag classes. Also add 'canonical' as an extra identifier.
  if (preg_match('/entity\.(\w+)\.canonical+/', Drupal::routeMatch()->getRouteName(), $matches)) {
    $variables['attributes']['class'][] = $matches[1];
    $variables['attributes']['class'][] = 'canonical';
  }
}