Hi all,

How can I add a class to in a module (not in a theme)? It's my module that determines the conditions for adding classes - and my theme that will show or hide elements based on those classes.

TIA.

Comments

nevets’s picture

You module can implement hook_preprocess_page(), set variables that represent the body id and class(es). Drupal already sets $body_classes which you could append to or override totally. Your theme will then need to use the variables as part of the body tag, example

<body id="<?php print $body_id; ?>" class="<?php print $body_classes; ?>">
extexan’s picture

@nevits, thanks for that. Is that the Drupal 7 way? - coz I'm using 6.

I looked in Drupal API and didn't find hook_preprocessor_page. I found all manner of template_preprocess_page and phptemplate_preprocess_page. None with "preprocessOR", as you typed in your post - so I guessed that was just a type-o and it really should be just "preprocess". But those are all dealing with themes, not modules, right?

Is there really no way to add a body class from within a module?

It's never too late to have a happy childhood. ;-)

nevets’s picture

Sorry type on my part (I corrected the post), modules can implement hook_preprocces_page. If your module was called mymodule, you would implement mymodule_preprocess_page.

shiv.godi’s picture

How to find the variables that represent the body id and class(es)?
Lets say, i'd like to style the node/2, node/3, etc... how would I identify unique body id or classes for each of the node?

Thanks

greenskunk’s picture

I know this is a little late but I didn't see an example for Drupal 6.
Adding a class or classes to the body of a page from a module. Please note that you could use either $vars or $variables based on the function argument. In this example, I used $variables and also note it is passed by reference.

function ModuleNameHere_preprocess_page(&$variables) {
  // string to array
  $classes = explode(' ', $variables['body_classes']);
  // add your class to the array
  $classes[] = 'my-special-css-class-name-here';
  // only apply a class on the front page
  if ($variables['is_front']) {
    $classes[] = 'my-homepage';
  }
  // only apply a class on a certain page ex. aDrupalSite.com/crazyModule/scream
  if (arg(1) == 'scream') {
    $classes[] = 'crazy-module-scream';
  }
  // assign it to the body_classes_array
  $variables['body_classes_array'] = $classes;
  // from array to string into body_classes
  $variables['body_classes'] = implode(' ', $classes); // Concatenate with spaces.
}

"It is a damn poor day when you don't learn something!" - Mr. Jones, teacher

mathieso’s picture

Thnx, GS. Helpful code.

Kieran

federosky’s picture

Here is the list of hooks that your module could implement,

and below, the link to the hook to pre-process theme variables from within a module.

Hope it helps!!
--
Federico