1

In Drupal 7 I would add a theme process function to add the body classes needed.

function template_preprocess_html(&$variables) {
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
}

In D8 this theme function exists but they don't have all the variables need for users.

2 Answers 2

4

Ok I think I figured this out as in Drupal 8 it uses TWIG to print the body classes for content types or users we need.

In the html.html.twig

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.hasPermission('administer')  ? 'isAdmin',
    user.getRoles()|join(' role_')
  ]
%}

Then make sure this line is added to the body classes

   <body{{ attributes.addClass(body_classes) }}>

So if the user is logged out we can use the role class to identify them.

   .anonymous { }

Or we can use the :not Css selector :not

   :not.user-logged-in {}
2

In html.html.twig and page.html.twig we have various variable available like logged_in, is_front, is_admin by default. Using these variables as condition we can add class to body tag. Some classes like path-frontpage, page-node-type-* are by default present in node and they is no need to add them explicitly.

Your Answer

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

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