Hello!

I'm trying to add the role of the currently logged in user to the body class. I've been trying to use the Drupal 7 code provided here: http://grasmash.com/article/drupal-add-current-users-role-body-classes, but I'm not having much luck getting this to work in Omega. Added the following to my omega sub-theme template.php file:

<?php
function mythemename_preprocess_page(&$vars) {
  if (
$vars['user']) {
    foreach(
$vars['user']->roles as $key => $role){
     
$vars['class'][] = 'role-' . drupal_html_class($role);
    }
  }
}
?>

I've also tried changing $vars to $variables, but that didn't work. Any tips?

Thanks!

Comments

dadderley’s picture

I would like Omega to do this as well.
I tried the same code that you did as well.
I played with it for a bit but could not make it work.

This is probably overkill, but the Context module makes this really easy to do.

Install it.
Add a context.
Then add a condition -- choose "User Role" -- choose the user roles you want.
Then add a reaction -- choose "Theme HTML" -- now you can create the body class that you want applied for the roles that you have chosen.

guysaban’s picture

This worked for me:

function themename_preprocess_html(&$vars) {
// ... there might be other stuff here ...
$body_classes = array($vars['classes_array']);
if ($vars['user']) {
foreach($vars['user']->roles as $key => $role){
$role_class = 'role-' . str_replace(' ', '-', $role);
$vars['classes_array'][] = $role_class;
}
}
}

roberskine’s picture

@guysaban's solution worked for me using a subtheme for seven. Just have to call it in your pages.tpl.php file. eg

<?php
 sevensubtheme_preprocess_html
();
?>
PCateNumbersUSA’s picture

Would love to see this integrated into omega4 as well.

fubhy’s picture

I'd consider a patch for this for Omega 4.

GiorgosK’s picture

for 3.1 I ended up using

<?php
function THEMENAME_preprocess_html(&$vars) {
 
$body_classes = array($vars['classes_array']);
  if (
$vars['user']) {
    foreach(
$vars['user']->roles as $key => $role){
     
$role_class = 'role-' . str_replace(' ', '-', $role);
     
$vars['attributes_array']['class'][] = $role_class;
    }
  }
}
?>

the difference from #2 is $vars['attributes_array']['class'][] = $role_class;

FranCarstens’s picture

Code in #6 works in Omega4 as well.

RgnYLDZ’s picture

For me I got all roles added as class.

EDİT:

Ok, sorry for that.

The administrator role was assigned as admin role in drupal. So I thougt it is showing it as extra role.

guile2912’s picture

Issue summary:View changes

Here is the code for Zen.
Also, it uses the drupal_clean_css_identifier function to make sure we respect the CSS grammar -?[_a-zA-Z]+[_a-zA-Z0-9-]*

function MYTHEME_preprocess_html(&$vars, $hook) {
  if ($vars['user']) {
    foreach($vars['user']->roles as $key => $role){
      $role_class = 'role-' . drupal_clean_css_identifier($role);
      $vars['classes_array'][] = $role_class;
    }
  }
}