Drupal - How do I add a class to the HTML "body" tag programmatically?

The preprocess functions can be implemented from modules, and themes.

The preprocess function that you need is hook_preprocess_html() and the variable to set is $variables['classes_array'], which is an array containing all the classes set for the <body> element. The content of the html.tpl.php file that is used by default by Drupal (if the theme doesn't use a different template file) is the following one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?></a>
  </div>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>

In your module you just implement the preprocess function as follows:

function mymodule_preprocess_html(&$variables) {
  $variables['classes_array'][] = "new-class";
}

template_process() then uses $variables['classes_array'] to populate $variables['classes'] with the following code:

$variables['classes'] = implode(' ', $variables['classes_array']);

 

Using a preprocess function in a module is preferable if your site uses more than one theme, or if the theme set for your site is not the one you created. In this case, you are able to set your custom CSS classes, and not lose them when updating the theme, or simply changing the default theme used by your site. If your site uses just a theme, and that theme is a custom theme you created, then you can implement the preprocess function in your custom theme. As you maintain the theme, the CSS classes are not lost when updating your theme.


add to MODULENAME.module and clear cache

function MODULENAME_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'custom-class';
}

Whilst you can do this through hook_preprocess_html, quite often you'll be in a completely different part of your codebase when you come to need this. If that's the case then I'd suggest that you use ctools_class_add instead:

ctools_class_add(array('class1', 'class2', 'class3'));

You can call that from anywhere as long as hook_preprocess_html hasn't yet run and the classes will be added.

Tags:

Theming

7