Add user role to body class in Drupal 8

Posted on 08/07/2016

There is a large list of helper classes that you can add to the <body> element in your theme. These classes will help you target specific contexts, nodes, user profiles, and allow you to combine these to your liking.

Here's what we will need to do:

  1. Add a template_preprocess_html() implementation to our theme.
  2. Get the roles of currently active user.
  3. Prepare the output we want to be shown in the template.
  4. Add this as attributes.

The following code needs to be added to your theme's .theme file:

  1. /**
  2.  * Implements hook_preprocess_html().
  3.  */
  4. function YOUR_THEME_preprocess_html(&$variables) {
  5.   // Get currently active user and his roles.
  6.   $account = \Drupal::currentUser();
  7.   $roles = $account->getRoles();
  8.   // The getRoles() method will return us the machine names, so there is no need
  9.   // to process roles names additionally. However, I suggest prefixing the names
  10.   // with "role-", so it's more obvious.
  11.   foreach ($roles as $role) {
  12.     $variables['attributes']['class'][] = 'role-' . $role;
  13.   }
  14. }

Then in your theme's html.html.twig file add:

  1. <body{{ attributes }}>

Note: you might want to pass TRUE to the getRoles() method, if you want to exclude the locked roles (anonymous and authenticated).

That's it!

Here's my answer on drupal.stackexchange.com.