How can I add body class based on path / page specific class - Drupal 9?

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. 

  1. Page Specific Class
  2. Custom Body Class 
  3. Body node ID class
  4. Extra body classes
  5. Node Class 
  6. Context
  7. Common Body Class
  8. .......etc

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
2 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.

Instagram Without API

Could not reach Instagram server