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

Last updated February 11, 2021

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