8

How do you add the class of the user role to the body tag, say in html.html.twig, in much the same way as you can add the path in How can I dynamically add URL or taxonomy to body class?

2 Answers 2

9

Here's how you could achieve that:

function YOUR_THEME_preprocess_html(&$variables) {
  // 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 ($variables['user']->getRoles() as $role) {
    $variables['attributes']['class'][] = 'role-' . $role;
  }
}

Then in your html.html.twig file you can set the attributes this way:

<body{{ attributes }}>

Note: you might want to pass TRUE to the getRoles() method, if you want to exclude the locked roles (anonymous and authenticated). You can read the docs on this method here.

2
  • I can confirm this works. Thanks! Just to clarify for other users, I am able to leave my body tag with the original setting (from Classy) as <body{{ attributes.addClass(body_classes) }} >.
    – Molesworth
    Mar 18, 2016 at 22:21
  • Glad it helped. If this solved your question, mark this answer as the solution, so others with the same question know this is what they're looking for. Mar 18, 2016 at 23:32
0

You can use Roles Classes module (works for the admin theme)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.