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?
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.
-
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 '16 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. – Aram Boyajyan Mar 18 '16 at 23:32