Classes and Attributes in Twig Templates for Drupal 8, Drupal 9, and Drupal 10

Last updated February 10, 2023
Theming9.5.x/10.0.x

Theme developers often need to add or remove classes and other attributes from an HTML tag. Template files handle this with a special attributes object that contains the attributes and their values, as well as a handful of powerful methods to help manage these attributes.

In this tutorial we'll cover:

  • Adding/removing classes from elements in a Twig template
  • The attributes object
  • Examples of common tasks using various helper methods on the attributes object