Drupal - Add attribute to html and body

Here is a preprocess alternative (maybe you will need access to some info to make custom html classes).

use Drupal\Core\Template\Attribute;

/**
 * Implements template_preprocess_html().
 */
function MODULE_OR_THEME_preprocess_html(&$vars) {

  if (is_array($vars['attributes'])) {
    $vars['attributes'] = new Attribute($vars['attributes']);
  }

  $vars['html_attributes']->addClass('goes-to-HTML-tag');
  $vars['attributes']->addClass('no-trans');
}

The attributes variable is an object, that has some methods available. One of them is addClass(), which allows you to add additional classes from a string or array.

<body{{ attributes.addClass('no-trans') }}>

To add arbitrary attributes to the html tag, you can use the setAttribute() method. Multiple attributes can be set by chaining additional calls to setAttribute():

<html{{ html_attributes.setAttribute('attrName1', 'attr1Value').setAttribute('attr2Name', 'attr2Value') }}>

Take a look at the community documentation on using attributes in templates.

You can also look at the node.html.twig template in the classy theme for an example of adding an array of classes with addClass():

{%
  set classes = [
    'node',
    'node--type-' ~ node.bundle|clean_class,
    node.isPromoted() ? 'node--promoted',
    node.isSticky() ? 'node--sticky',
    not node.isPublished() ? 'node--unpublished',
    view_mode ? 'node--view-mode-' ~ view_mode|clean_class,
  ]
%}
<article{{ attributes.addClass(classes) }}>

Tags:

Theming

8