Twig Best Practices in Drupal
Practical template organization, includes, variables, debugging, and mistakes that make themes brittle.
Twig should make markup understandable, not hide application logic. The best templates are boring: their variables are prepared, their structure is semantic, and their reuse follows component boundaries.
Know the template hierarchy
Start with theme debug output to see candidate template names and suggestions. Override the narrowest template that represents the design decision; broad overrides create accidental coupling.
Prepare, then print
Use preprocess hooks to derive presentation variables and Twig to escape and arrange them. Avoid reaching into deeply nested entity internals from templates. Includes are useful for components; macros are best reserved for pure markup helpers.
Debug without weakening production
Enable Twig debug and disable caching only in local settings. Inspect available variables, confirm cache rebuilds, and remove debug configuration before deployment.
Working example
{% include '@circuitfolio/components/badge.html.twig' with {
label: difficulty,
modifier: difficulty|clean_class
} only %}Key Takeaways
- Override the narrowest appropriate template.
- Prepare complex variables outside Twig.
- Use
onlywith includes to make dependencies visible.