How can I properly set a class for body tag for the front page?
mytheme_preprocess_html() have an access to body attributes, but it doesn't know if the page is front.
And mytheme_preprocess_page() have is_front, but I can't set attributes in there.

Comments

naveenvalecha’s picture

Sandbox module available https://www.drupal.org/sandbox/rahulbaisanemca/2583147 Might be that will work you can also get idea from it

--
Naveen Valecha
http://valechatech.blogspot.in

Jeff Burnz’s picture

Are you using Classy as a base theme? If so then you get such classes automatically, otherwise you can add to your html.hmtl.twig template:

  {%
    set body_classes = [
      not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    ]
  %}
  <body{{ attributes.addClass(body_classes) }}>

This will give you a "path" class, one of which will be "path-frontpage". Note this is recommended way to add classes in D8.

If you want to do this in PHP then you have to use hook_preprocess_html(), and add an attribute, e.g. do something like this:

use Drupal\Component\Utility\Html;

/**
 * Preprocess variables for html templates.
 */
function HOOK_preprocess_html(&$variables) {
  $path_class = !$variables['root_path'] ? 'path-frontpage' : 'path-' . Html::getClass($variables['root_path']);
  if (isset($path_class)) {
    $variables['attributes']['class'][] = $path_class;
  }
}