Sometimes it's useful to add body classes based on the current Drupal user's roles.
This article shows how to do this by adding or modifying a theme_preprocess_html()
implementation in your .theme
file.
No twig modifications required.
Step 1: implement theme_preprocess_html()
In your theme's MYTHEME.theme
file, add the following preprocess function:
/**
* Implements hook_preprocess_html().
*/
function MYTHEME_preprocess_html(&$variables) {
$roles = \Drupal::currentUser()->getRoles();
foreach ($roles as $role) {
$variables['attributes']['class'][] = "role-{$role}";
}
}
→ Be sure to replace MYTHEME with the name of your own theme.
→ Be sure to clear your caches.
Assuming the current user has the administrator role, the body classes for each of the pages this user loads will now also contain:
- role-authenticated
- role-administrator
Step 2: add styles
You can now add styles targeted at specific user roles.
We use this technique to render certain administrative / debugging styles for admin users.
Here's an example: highlighting images without alt descriptions.
.role-administrator img:not[alt],
.role-administrator img[alt=""] {
border: solid red 2px;
}
If you liked this article, you'll love our courses on Drupal 8/9 Site Building, Module Development, and Theme Development.
Top comments (1)
Then in your theme's
html.html.twig
file add:<body{{ attributes }}>