DEV Community

TrainingCloud.io
TrainingCloud.io

Posted on • Edited on

3 2

Drupal 8/9: Adding CSS body classes based on the current user's roles

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}";
  }
}
Enter fullscreen mode Exit fullscreen mode

→ 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;
}
Enter fullscreen mode Exit fullscreen mode

If you liked this article, you'll love our courses on Drupal 8/9 Site Building, Module Development, and Theme Development.

TrainingCloud: Drupal and PHP training for (aspiring) developers

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (1)

Collapse
 
mahmoudsayed96 profile image
Mahmoud Sayed

Then in your theme's html.html.twig file add:
<body{{ attributes }}>

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay