How do you add a class to a Twig template in Drupal 8?

Adding CSS classes to templates allows you to target templates or parts of the template in your CSS files.

For example, if you want a different background colour per content type, then you need a way to identify each content type with a CSS selector. By default the node template includes a class for each content type, making it easy for you to target each one. You’ll see this in action later on in this tutorial. You will also learn how to create your own classes.

Adding a single class

To add a class, pass in the class name as an argument to the attributes.addClass() function.

<div {{ attributes.addClass('classname') }}>

</div>

Adding multiple classes

To add multiple classes to an element, create an array with all of the class names. To create an array in Twig, use the set tag followed by the name of the array.

{%
  set classes = [
    'content',
    'node',
    'custom',
  ]
 %}

And then pass that array to the attributes.addClass() function.

<div {{ attributes.addClass(classes) }}>

</div>

Classes are merged with existing classes

If there are any existing classes, the new classes will be merged. Therefore, all the classes will be added to the element.

Removing a class

You may decide that you’d like to remove one of the existing classes. To do that, you can use the attributes.removeClass() function.

<div {{ attributes.addClass(classes).removeClass('node') }}>

</div>

Two real world examples

In your code editor, head over to the templates in the Classy theme (core/themes/classy/templates).

Single class

Open up field/time.html.twig. This is an example of a single class being added to the time element.

<time{{ attributes.addClass('datetime') }}>{{ text }}</time>

Multiple class array

Open up layout/region.html.twig. The classes array:

{%
  set classes = [
    'region',
    'region-' ~ region|clean_class,
  ]
%}

In this example, there are two classes. The first one is a simple one called ‘region’. The second one looks more interesting:

'region-' ~ region|clean_class,

Let’s break this down:

  • 'region-': a simple sting
  • ~ is a Twig operator that concatenate two strings together
  • region: the region variable. It will be replaced with the actual region (e.g. block)
  • |: A pipe that separates a variable (region) from a filter (clean_class)
  • clean_class: a filter that will remove invalid characters from HTML classes

If you have a block in the header region, then the above code will add a class called region-header.

<div class="region region-header">

Node class

The final example is the classes added to the article element in the node template.

Open up content/node.html.twig. This is another example of multiple classes.

{%
  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,
  ]
%}

As mentioned in the example at the top of this tutorial, the node template will have a class for the content type, making it easy for you to specify styles on for specific content types. That is defined with this line:

'node--type-' ~ node.bundle|clean_class,

A content type is a type of bundle in Drupal. So node.bundle will return the content type machine name. Just like the field example, this is passed through the clean_class filter.

If you are viewing an article node, the class added to article will be:

node--type-article

There are also four conditions that check if something exists before adding the class. For example:

node.isPromoted() ? 'node--promoted',

This checks if the node is promoted to the frontage. If it is, it adds the node--promotedclass.

not node.isPublished() ? 'node--unpublished',

This checks if the node is not published. If it isn’t published, it adds the node--unpublished class.

Outro

Hopefully this tutorial has helped you understand how you can add classes to Twig templates. I encourage you learn from more examples by having a look at more templates (in the Classy theme, or another theme).

Comments

It is highly useful material. Thanks a million..

I really bookmark this blog post ,this post really helps me in website development project.Very informative post.

Also very useful and apparently not easily findable "How to add attributes to a link":
{% set attributes = attributes.addClass('button') %}
{{ link(link_text, link_url, attributes) }}

The tutorial surely helps but I cannot concatenate two classes in a twig file based on field.html.twig

This twig file targets an image field in a content type which has an entity reference to a taxonomy term.

Here is the class related to the image:
.my-image img {
border-left: 3px solid;
}

Here are two taxonomy term id's classes:
.tid-1 {
color: blue;
}
.tid-2 {
color: red;
}

The idea is to set a 3 pixels border on the image; the border color is blue or red depending on the taxonomy term.

Hi Blair, Thanks for this. Bartik's comment.html.twig https://pastebin.com/D70cyHNp has the class "comment__author" - how would I say: add the class "red" if the comment author has the role "administrator"?

New comments for this tutorial have been turned off.