6

I need to add class="no-trans" to body, also edit the html tag. How I can edit the {{ html_attributes }} and {{ body_attributes }} ?

my html.html.twig

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ body_attributes }}>

2 Answers 2

6

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) }}>
2
  • what is the benefit of using this setAttribute(... over just attr1="value" or addClass class="myClass" ?
    – J. Doe
    Commented Dec 30, 2015 at 12:36
  • 1
    Classes and attributes may already be added in preprocess, so if you add class="..." or attr1="..." directly in the template, the attribute may then appear twice in the output. setAttribute() should also ensure that the value is correctly encoded for use as an attribute value, which may be important if it is a dynamic value.
    – gapple
    Commented Dec 31, 2015 at 5:39
9

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');
}
0

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.