Add class to body based on path alias in Drupal 8

You, DrupalDrupal theme
Back

We can simply implement template_preprocess_html in the theme to make this happen.

/**
 * Implements hook_preprocess_html().
 */
function THEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  $path_alias = ltrim($path_alias, '/');
  $variables['attributes']['class'][] = 'path-' . \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);
}
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.