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:
- Add a
template_preprocess_html()
implementation to our theme. - Get the roles of currently active user.
- Prepare the output we want to be shown in the template.
- Add this as attributes.
The following code needs to be added to your theme's .theme
file:
/** * Implements hook_preprocess_html(). */ function YOUR_THEME_preprocess_html(&$variables) { // Get currently active user and his roles. $account = \Drupal::currentUser(); $roles = $account->getRoles(); // The getRoles() method will return us the machine names, so there is no need // to process roles names additionally. However, I suggest prefixing the names // with "role-", so it's more obvious. foreach ($roles as $role) { $variables['attributes']['class'][] = 'role-' . $role; } }
Then in your theme's html.html.twig
file add:
<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.