2

Using Drupal 8 and Bootstrap sub-theme.

I see that classes are being added to my divs in the page template file using the following:

<section{{ content_attributes.addClass(content_classes) }}>

That's great. But what if I wanted to add additional classes to these div tags. How would I do that...in my .theme file somehow?

3

OPTION 1

In your template file, you could find the set content_classes and add another class name to the list.

{%
  set content_classes = [
    'class-name',
    'class-name-other',
  ]
%}
<section{{ content_attributes.addClass(content_classes) }}>

OPTION 2

In your .theme file

function themename_preprocess_html(&$variables) {
  $variables['content_attributes']['class'][] = 'class-name-other';
}

Note: This preprocess is for the html.html.twig file, you need to use the correct preprocess depending on your template file name.

If it's the node.html.twig then use function themename_preprocess_node(&$variables)

If it's the page.html.twig then use function themename_preprocess_page(&$variables)

2
  • In option 2, once this new class gets added in array, then we need to add that class to that particular div or element in .tpl.php Or twig file, right? This I am asking just for my understanding/knowledge. Thanks.
    – CodeNext
    Aug 22 '16 at 8:37
  • 1
    @CodeNext yes that is correct, you would do <div {{ content_attributes }}> ...... </div> or some element <p {{ content_attributes }}> ...... </p>, <body {{ content_attributes }}> ...... </body>
    – No Sssweat
    Aug 22 '16 at 8:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.