-1

I want to add a extra unique class in body tag so that it will come only for the anonymous user.

How to add it?

3

The proper way to do this is in a preprocess hook:

function MYTHEME_preprocess_html(&$vars) {
  if (user_is_anonymous()) {
    $vars['classes_array'][] = 'foo-class';
  }
}

Don't try to make this decision in a template file, you'll find it doesn't work properly when you have caching enabled. Or it'll break your caching entirely for the page.

  • 1
    In fact, core already uses this exact method in template_preprocess_html and either adds logged-in or not-logged-in, so a class should already be there. – mpdonadio Oct 14 '15 at 15:23
  • Yep you're spot on @MPD, I just checked a few sites and they all have that class. Probably worth an answer actually – Clive Oct 14 '15 at 15:25
2

Core already does this for you. If you examine includes/theme.inc, you will find the implementation for template_preprocess_html() which is run by default before module and theme specific versions. In it is this code blip

function template_preprocess_html(&$variables) {
  // ...
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
  // ...
}

So, there are already body classes, logged-in and not-logged-in, added for you. If those classes is not there, something is altering the $variables['classes_array'] in a naughty way.

  • @Vicky8888 - That's the right answer. – leymannx Oct 14 '15 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy