Drupal: Adding current user's role to the <body> tag, as a class

Thu, 10/02/2014 - 16:01 -- admin

This is something handy I've been using for a while when developing Drupal sites, and I thought I'd share it!  We're basically going to be adding a small function to our site, that is going to print out the current user's role as a class, on the <body> tag.  The snippet I'm going to share will work with Drupal 7 sites that are running the Omega theme (or using a subtheme of the Omega base theme).

  1. You will need to open up your theme's template.php file (usually located at sites/all/themes/[THEME_NAME]/template.php, or sites/[SITE_SPECIFIC_FOLDER]/themes/[THEME_NAME]/template.php)
  2. Add the following function to the template.php file (replacing [THEME_NAME] with your actual theme name):
    function [THEME_NAME]_preprocess_html(&$vars) {
      if ($vars['user']) {
        foreach($vars['user']->roles as $key => $role){
          $vars['attributes_array']['class'][] = 'role-' . drupal_html_class($role);
        }
      }
    }
  3. Save the template.php file, and clear your Drupal cache
  4. You should now see the current user's role printed out on the <body> tag, as a class.

The function runs before the HTML is outputted to the page, when Drupal is deciding what the DOM structure of the page your loading should look like.  If the user variable exists, it loops through all user's roles, and prints them out as a class on the <body> tag.  We have to use $vars['attributes_array'] in this function, because this is how the Omega theme accesses attributes.

With this function in place, I find it much easier to do role-based styling -- since the current user's role will dynamically be printed out as a class on the <body> tag.  I've also used this for debugging purposes in the past (i.e. Hide debug output for all users except those that have the "admin" role).  Hope this helps a few people.