Drupal 8 Tip: Add unique class to the body tag from page path (or route)

Megan's picture

She has: 11,421 posts

Joined: Jun 1999

To add a custom, unique class to the body tag based on the page's path alias (route name), first add the following to your .theme file:

function yourtheme_preprocess_html(&$variables) {
  $variables['route'] = str_replace('.','-',\Drupal::routeMatch()->getRouteName());
}

If you don't already have a theme override for the html.html.twig file, create one by copying the html.html.twig file from your base theme (e.g. classy). Then, add the route variable to the body_classes variable:

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'page-frontpage' : 'page-' ~ root_path|clean_class,
    node_type ? 'node--type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
   <strong>route,</strong>
  ]
%}