Adding custom body classes to the standard Drupal output
Here's a great trick if you need to add custom classes to the body tag output of your Drupal theme. This goes above the standard body tag output using a line like this in your page.tpl.php
<body class="<?php print $body_classes; ?>">
Which only creates the usual body classes like:
<body class="front logged-in page-node one-sidebar sidebar-right">
These are great for adding custom CSS formatting to a page. But I have sometimes found the need to add my own classes above the standard Drupal output, specifically if I need a body class attribute when custom regions are displayed. Here's how:
Open or create the template.php in your themes folder and add the following code.
function YOUR-THEME_preprocess_page(&$vars, $hook) {
// Pull in all the body class variables currently set
// into the variable in this function so it can be edited
$body_classes = array($vars['body_classes']);
// Check to see if the region is being used and if so
// then adds the region CSS class to the variable.
if ($vars['custom_region']) {
$body_classes[] = 'custom-region';
}
// Add the new body classes to the existing variable and
// push back into the default variable used in theme creation.
$vars['body_classes'] = implode(' ', $body_classes);
}
Thats it. You will need to empty the theme cache before the changes take place. But now you should see the following in your source code.
<body class="front logged-in page-node one-sidebar sidebar-right custom-region">
If the function 'preprocess_page' is already being called in your template.php you will need to combine these code blocks together because you can't call the same function twice.
How cool is that?!

Add new comment