How to auto-add body classes in Drupal 8

Submitted by Dan Grant on Sun, 03/26/2017 - 15:37

When creating the custom theme for this site, I decided to use Stable as the base them instead of using Zen (my preferred theme in Drupal 7 the past couple years), Bootstrap, etc.

Stable doesn't give many classes by default, unlike the Classy base theme.  In order to auto-add simple classes to different pages (so as to be able to easily target them with CSS), do two things:

1 - Copy the "html.html.twig" file from "core/themes/stable/templates/layout" into your custom theme's template directory (mine is at "themes/custom/xq42/templates/"

2 - Add the following code to the html.html.twig file you just copied:

 

{%
  set body_classes = [
    logged_in ? 'logged-in',
    not root_path ? 'frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'node--type-' ~ node_type|clean_class,
  ]
%}

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

 

The cache will need to be rebuilt for this code to take effect.

An example of what this does can be seen by inspecting (Google "Inspect". Firefox "Firebug", etc.) the /blog page here - you'll see the class "path-blog" has been added to the body element.

 

source --> http://stackoverflow.com/questions/34145149/add-body-class-to-node-in-drupal-8

 

blog_tags