Oct 19, 2020 in Drupal 8

There are two ways of adding body classes. The first is to add them in twig, the second is to provide additional classes in mytheme.theme.

Option 1: html.html.twig

Extend the current body class with the following:

 {%
  set body_classes = [
  logged_in ? 'user-logged-in',
  not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
  node_type ? 'page-node-type-' ~ node_type|clean_class,
  db_offline ? 'db-offline',
  current_path ? 'context' ~ current_path|clean_class,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>

Option 2: define in mytheme.theme

In your mytheme.theme add:

function mytheme_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $variables['current_path'] = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
}

Then, html.html.twig:

 {%
  set body_classes = [
    {{ current_path }}
  ]
%}
<body{{ attributes.addClass(body_classes) }}>

 

Comments