Summary of "Getting Started with Twig Templates in Drupal CMS"
Getting Started with Twig Templates in Drupal CMS
Core message
- Twig is the templating engine used by Drupal 8+ (a Symfony component). It is modern, flexible, and safer than raw PHP templates because it escapes output by default.
- When building Drupal themes you’ll mostly need to know:
- Twig syntax
- How Drupal passes variables into templates
- How to debug templates/variables
- How to override templates in a theme (or subtheme)
- How to reuse/extend Twig templates
- Several contributed modules add very useful Twig utilities.
Tip: Twig auto-escapes output by default — avoid using
|rawunless you fully trust the content.
Key concepts and syntax
Basic Twig syntax
- Output a variable:
{{ variable }} - Control structures:
- If:
{% if condition %} ... {% endif %} - For:
{% for item in items %} ... {% endfor %}
- If:
- Comments:
{# comment #} - Filters:
variable|filter(pipe). Common examples:|raw(renders raw HTML — use cautiously)|trim,|format,|striptags,|join
- Loop helpers:
loop.firstandloop.lastare available insideforloops. - Debug helper:
dump(variable)— prints debug output inside Twig templates.
Example:
{% for item in items %}
{{ item.title|trim }}
{% endfor %}
Escaping and raw
- Output is escaped by default.
- Use
|rawsparingly and only when you trust the content. - You can chain filters to strip tags or allow specific tags before using
|raw.
Drupal-specific templating concepts
Template hierarchy / suggestions
- Enable Twig debugging in Drupal to get HTML comments that show template path and suggestion names (e.g.,
html → page → region → block → node → field → media → image). - Page structures are nested — a single piece of markup can be rendered via multiple template layers (region → block → field → media → image formatter).
Variables and render arrays
- Drupal commonly passes a top-level
contentvariable that contains many renderable sub-elements (fields, blocks, layout builder content). - To exclude keys from
contentwhen rendering, use thewithoutfilter:{{ content|without('comment') }}
- Many fields are nested entity references. To access raw values you often traverse entities, for example:
node.field_featured.entity.field_image.entity.uri.value- Wrap with
file_url()for a usable URL:file_url(node.field_featured.entity.field_image.entity.uri.value)
- Image alt text and other properties are available via the same entity traversal (e.g.,
...alt).
Attributes and classes
- Templates often receive an
attributesvariable.- Add classes:
attributes.addClass('my-class')or assign:attributes = attributes.addClass('my-class') - Remove classes:
attributes.removeClass(...)
- Add classes:
- Preprocessors (PHP functions like
theme_preprocess_node) are commonly used to add classes/variables before they reach Twig.
Debugging Twig in Drupal
- Enable Twig debugging and disable caching in Development settings to see Twig suggestions and to see template changes quickly.
- Clear Drupal cache often:
drush cr - Inspect compiled Twig (templates compiled to PHP) in
sites/default/files/php(or equivalent) to understand how Twig compiles. - Interactive debugging:
- Use
dump()inside Twig to inspect arrays/variables (note: front-end styling can make dumps hard to read). - Use Xdebug + a module (e.g.,
twig_xdebug/ twig debug helper) to set breakpoints and view the variable context from a template render.
- Use
- Twig Tweak provides a Drush command
twig_tweak debugthat lists available Twig functions/filters/tests and template paths.
Template reuse and extension patterns
- Include:
{% include 'template-name.html.twig' %}— pull in another template file for reuse.
- Extend and block:
- Base template:
{% extends 'base.html.twig' %} - Define blocks:
{% block content %}...{% endblock %} - To keep parent content and add more: use
{{ parent() }}inside a block. - Use small blocks inside large templates so child templates can override just a block instead of copying the whole file.
- Base template:
- Prefer
include/extends/blockfor reusability rather than copying entire templates.
Example:
{% extends 'base.html.twig' %}
{% block content %}
{{ parent() }}
<p>Additional content</p>
{% endblock %}
Overriding templates in a theme or subtheme (common workflow)
- Turn on Twig debugging and disable caching: Admin → Configuration → Development → Development settings.
- Inspect the page and read the theme debug comments to find the correct template suggestion(s).
- Copy the core/contrib template file (e.g.,
core/themes/.../templates/node.html.twigorhtml.html.twig) into your theme’stemplates/directory (keep proper folder structure as needed). - Clear caches:
drush crand verify the debug comment now points to the theme’s template. - Modify the template in the theme. Use small blocks or includes where appropriate for reusability.
- If you need to add classes or computed values site-wide, implement theme preprocess functions in PHP (e.g.,
theme_preprocess_node) and add data to the variables array so Twig receives simpler variables.
Useful contributed modules & tools
- Drush (+ Drush generate theme) — scaffolding and CLI utilities.
- DDEV — local development environment.
- Twig Field Value — helpers/filters to read field labels/values safely (e.g.,
field_label,field_build_value,safe_join). - Twig Tweak — powerful Twig helper module (render entities, views, regions, images; includes
twig_tweak debug). - Bamboo (Bamboo Twig modules) — modular Twig helper functions (absolute file URLs, etc.).
- Token + Bamboo token integration — render tokens in Twig.
- Twig UI — admin UI that can edit Twig templates from the backend (use with caution).
- Twig Template Suggestions module — enhances suggestion possibilities for more granular overrides.
- Xdebug + a Twig debugging module (e.g.,
twig_xdebug) — for stepping through and inspecting the twig render context in an IDE.
Tools mentioned: PHPStorm, OBS, Ream, TikTok.
Practical code and commands
- Turn Twig debugging on and caching off:
- Admin → Configuration → Development → Development settings (enable twig debugging, disable caching)
- Clear cache:
drush cr - Theme generator (example using DDEV):
ddev drush generate theme(follow interactive prompts) - Convert a Drupal file URI to a usable URL/path in Twig:
file_url(value)
- Example (render a block using Twig Tweak):
{{ drupal_entity('block_content', '1') }}
- Use
twig_tweak debug(Drush command) to list Twig Tweak provided functions, filters, tests, and template paths.
Common pitfalls & advice
- Twig auto-escaping can make debugging confusing — don’t use
|rawunless necessary and safe. - Caching can mask template changes — either disable cache during development or clear caches frequently.
- Template suggestion names can be long; use twig debugging comments (or the Twig template suggestions module) to find the exact file name to override.
- If you don’t want to override templates just to add a class, prefer adding the class in a preprocess function instead.
- Use
include/extend/blockto keep templates maintainable and DRY. - When
dump()output is unreadable because of front-end styles, use Xdebug/IDE breakpoints to view the variables cleanly.
Resources recommended
- Twig official documentation (syntax, filters, tests).
- Contributed module docs (Twig Tweak, Twig Field Value, Bamboo).
- Community resources and Google searches for entity/field paths — experience builds this knowledge.
Speakers / sources referenced
- Presenter: WebWash (live-stream host; session author/presenter — examples referenced themes named “Olly / Oliver Vero WW”)
- Projects / sources mentioned:
- Twig (Symfony component)
- Drupal core theming (8+)
- Drush, DDEV, PHPStorm, Xdebug
- Contributed modules: Twig Field Value, Twig Tweak, Bamboo (Bamboo Twig), Token, Twig UI, Twig Template Suggestions,
twig_xdebug - Streaming/tools: OBS, Ream, TikTok
- WebWash website / YouTube channel (presenter’s resources)
Category
Educational
Share this summary
Is the summary off?
If you think the summary is inaccurate, you can reprocess it with the latest model.
Preparing reprocess...