10 Twig Tricks for Better Drupal Theming

About the Author

Ahmad Estaitia

Associate Software Engineer

Ahmad Estaitia is an Associate Software Engineer at Vardot with experience in Drupal development, frontend theming, and building accessible, responsive web solutions. He works on digital platforms and content-driven applications, contributing to scalable implementations, UI components, and performance improvements across web projects.

FAQs

Enable Twig debug mode in Drupal 11 from the Development settings page at /admin/config/development/settings by checking "Twig development mode," or run drush theme:dev on. Both turn on debug output, template suggestions in HTML comments, and the dump() function. On Drupal 10.3 and later, avoid setting debug in the primary services.yml, which overrides the admin UI; use development.services.yml for committed local config. Never enable debug in production.

The Twig include() function renders a template or component and outputs its result, and it's the recommended choice for most Drupal theming because it accepts named arguments. The {% embed %} tag is for cases where you need to fill a component's slots using Twig blocks, since embed lets you override block content inside the included template. For Single Directory Components, use include() when passing props and embed when filling slots.

No, Single Directory Components do not replace Twig templates in Drupal; they sit alongside them. Drupal templates still use naming conventions to render entities, blocks, and fields, and they call components with include() or embed. SDC, stable in core since Drupal 10.3, handles reusable UI and auto-attaches component assets, so templates get shorter and reuse improves, but the template layer remains how Drupal maps content to markup.

Create dynamic CSS classes in Twig by building an array of class names and passing it to the attributes object or create_attribute(), using the clean_class filter to sanitize values. For example, set a classes array with conditional entries, then output {{ attributes.addClass(classes) }}. This keeps class logic readable and avoids string concatenation. The attributes object also preserves classes Drupal already assigned to the element.

You do not need attach_library() for assets that belong to a Single Directory Component, because Drupal automatically detects the component's .css and .js files and attaches them whenever the component renders. Reserve attach_library() for theme-level assets not owned by a single component: global styles, a typeface, or a script that spans the whole site. This split keeps component styling self-contained and prevents loading assets on pages that don't use them.

Join the conversation +