Drupal - How to add classes to BODY tag dynamically based on page path/depth?

To expound on Nikhil Mohan's answer, you can implement template_preprocess_html() inside your theme's template.php file. Read the documentation on Overriding Themable Output to understand the basics of what is going on here.

Within this function, you have access to the variable $vars['classes_array'], which holds a list of classes that will be applied to the HTML <body> tag on the page.

Unfortunately, information about the current page's location in the menu is not immediately available. You could use menu_get_item() and then menu_get_ancestors() to get this information, but that is a lot of processing power for something that we can probably get to with a simpiler approach.

Assuming you are using the pathauto module to automatically create semantic paths for your content pages based on the menu path (i.e., your Melbourne Theme Parks page would have the path 'melbourne/theme_parks') you can use the page's path to create the classes you are looking for:

function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  } 
}

That's it. Drupal will now look at the path alias of the current page and add a class to the <body> tag for each chunk of the path alias.

Tags:

Theming

7