Come together with the global Drupal community in Rotterdam, 28 Sept – 1 Oct 2026. Sessions, contribution, connection, and Early Bird savings until 8 June.
Just like Drupal 7, you can affect the output of certain HTML via preprocess functions. For example, if you wanted to add a class to a menu and preferred to do this at the PHP level, you can. This is a good way to alter theme-specific markup. If you want to add or edit theme-independent markup, you should create a custom module instead.
Many Twig templates will have one or more Attribute objects passed in as variables. The job of the Attribute object is to store a set of HTML attributes, providing the developer helpful methods to interact with that data and allow for easy printing of the attributes. For example, attributes.addClass('myclass') makes it easier to add one class without worrying about precise string concatenation.
Generally, attributes in a template should look something like this: