TransWikia.com

How can I add a CSS class to the body tag based on the current path alias?

Drupal Answers Asked by JeroenT on October 26, 2021

Is it possible in Drupal 8, to add a CSS class to the <body> tag based on the current path alias?

One Answer

In your theme, you can add the following code in template_preprocess_html:

$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'][] = DrupalComponentUtilityHtml::cleanCssIdentifier($path_alias);

Answered by JeroenT on October 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP