It's a simple 3 line code to achieve adding the body class based on the URL. Sometimes, we need to overwrite the existing styles based on the page. so, we need the page specific class.
Go to your THEME_NAME.theme file & add this below HOOK.
/**
* Implements hook_preprocess_html().
*/
function THEME_NAME_preprocess_html(&$variables) {
// Get the current path
$current_path = \Drupal::service('path.current')->getPath();
$internal_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
// Assign it to body class
$variables['attributes']['class'][] = str_replace("/", "", $internal_path);
}
Make it simple :)
We have Similar projects different attempts, but we don't need to enable those modules. If you want any specific requirement then we can go ahead.
- Page Specific Class
- Custom Body Class
- Body node ID class
- Extra body classes
- Node Class
- Context
- Common Body Class
- .......etc
- Add new comment
- 1665 views
Comments
Add page prefix to the class.
Submitted by Moin (not verified) on Thu, 11/24/2022 - 16:15
It helps a lot by adding page- prefix to the class.
Add new comment