Drupal : Add classes to $body_class

$body_classes variable and how it’s used

By default, Drupal provides Drupal themes coders with a variable $body_classes which contains a list of space separated keywords that you can use to style your page depending on different factors including the user status (logged in or not), the page he is viewing (frontpage, node, page, story…).

Make use of $body_classes on your theme like this

<body class="<?php print $body_classes; ?>">

Here are a few exmaples of $body_classes for different visitors:

  • $body_styles: front not-logged-in page-node no-sidebars
  • $body_styles: not-front logged-in page-node node-type-blog no-sidebars

You can easily tell that the first line corresponds to a user not logged in, he is viewing the frontpage, the 2nd line is from a user who is logged in and is probably reading a blog post. Both visitors are viewing a page with no sidebars (the admin of the site decided so)

It’s very easy, using these classes to present things differently depending on what suits your needs (user status, current node type, sidebars)

You can find more about the logic behind this variable one the Drupal API Reference

Add more classes to $body_classes

Now what if you need more than those default classes, you can think of many examples; I – as the administrator of a Drupal site – want a big red banner to remind me to logout if I’m using my administrator account instead of my normal account.

The proper way to this is by using the theme hook template_preprocess_page like this (replace theme_name), we add the function theme_name_preprocess_page to our template.php file, Drupal will automatically run that code and add the new classes that we want:

<body class="<?php
function theme_name_preprocess_page(&$variables) {
  $body_classes = array($variables['body_classes']);
  // if the user is the admin add the class is_admin
  if ($variables['is_admin']) {
    $body_classes[] = 'is_admin';
  // ... more magic here if you want to add  more classes ...
  $variables['body_classes'] = implode(' ', $body_classes);

Now you can add more if clauses to the function to have the classes you need.

Leave a comment

Your email address will not be published.