Question

I have a block in drupal 6 with php code which I would like to add a certain class to the body, but how can I achieve this?

Is it even possible to do this outside the preprocess function?

Show if the following PHP code returns TRUE (PHP-mode, experts only).

<?php 
$url = request_uri();
if (strpos($url, "somestring"))
{
    $vars['body_classes'] .= ' someclass';
}
elseif ( arg(0) != 'node' || !is_numeric(arg(1)))
{ 
    return FALSE;
}

$temp_node = node_load(arg(1));
$url = request_uri();

if ( $temp_node->type == 'type' || strpos($url, "somestring"))
{
    return TRUE;
}
?>
Was it helpful?

Solution

Upfront remark: If your actual condition is depending on the request URL, as your example shows, then I agree with Terry Seidlers comment that you should just do this within a *_preprocess_page() implementation in a custom module or within your themes template.php.

More generic option:

AFAIK, this is not possible from outside a *_preprocess_page() function out of the box. However, you can easily add this functionality with a helper function:

/**
 * Add a class to the body element (preventing duplicates)
 * NOTE: This function works similar to drupal_add_css/js, in that it 'collects' classes within a static cache,
 * adding them to the page template variables later on via yourModule_preprocess_page().
 * This implies that one can not reliably use it to add body classes from within other
 * preprocess_page implementations, as they might get called later in the preprocessing!
 *
 * @param string $class
 *   The class to add.
 * @return array
 *   The classes from the static cache added so far.
 */
function yourModule_add_body_class($class = NULL) {
  static $classes;
  if (!isset($classes)) {
    $classes = array();
  }
  if (isset($class) && !in_array($class, $classes)) {
    $classes[] = $class;
  }

  return $classes;
}

This allows you to 'collect' arbitrary body classes from PHP code anywhere during the page cycle, as long as it gets called before the final page preprocessing. The classes get stored in the static array, and the actual addition to the output happens in a yourModule_preprocess_page() implementation:

/**
 * Implementation of preprocess_page()
 *
 * @param array $variables
 */
function yourModule_preprocess_page(&$variables) {
  // Add additional body classes, preventing duplicates
  $existing_classes = explode(' ', $variables['body_classes']);
  $combined_classes = array_merge($existing_classes, yourModule_add_body_class());
  $variables['body_classes'] = implode(' ', array_unique($combined_classes));
}

I usually do this from within a custom module, but you could do the same within a themes template.php file.

With this in place, you can do the following almost anywhere, e.g. during block assembly:

if ($someCondition) {
  yourModule_add_body_class('someBodyClass');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top