Twig is a template engine for PHP, which is the language used in Drupal. Twig can be used for templates in generic PHP applications as well as Drupal themes. The Drupal implementation of Twig is the same as regular Twig with a couple of Drupal additions. Drupal adds some custom filters and automatically handles the render pipeline for you. Anything you can do in regular Twig you can also do in Drupal's implementation of Twig.
Example tasks
- Customize markup in templates for a Drupal site
- Use dynamic data from variables within template files
- Customize markup in PHP applications that use Twig for templates
Confidence
Resources on this page use both generic PHP applications as well as template files from Drupal 8 themes for context and examples. The Twig that is used in generic PHP applications can be used in Drupal templates as well. Note that Drupal has extended Twig and provides some Drupal-specific filters and functions. In some cases, these Drupal-specific functions or filters are preferable to their generic Twig counterparts.
Note: Drupal 10 uses Twig 3.x. (Drupal 9 uses Twig version 2.x and Drupal 8 uses Twig version 1.x. Be sure to use the appropriate version when consulting Twig's official documentation.
Drupalize.Me resources
Related tutorials
Using Twig's attach_library
function, you can attach asset libraries of CSS or JavaScript files. Learn more about asset libraries, or jump straight to the relevant section on attach_library
in Attach a Library.
External resources
-
Twig 3.x Documentation (twig.symfony.com)
- Official documentation for Twig. Contains a reference for tags, filters, functions, and tests, as well as information for template designers and developers looking to extend Twig with custom functionality.
-
Twig for Template Designers
- This document describes the syntax and semantics of the template engine and will be most useful as reference to those creating Twig templates.
-
Twig in Drupal (Drupal.org)
- Guide to community-contributed documentation on Twig as it is used in Drupal.
-
Preparing for use of Twig 2 in Drupal 9 (drupal.org)
- The update from Drupal 8 to Drupal 9 includes updating the Twig dependency from Twig 1 to Twig 2. Unfortunately due to how composer dependencies work for Drupal 8 sites, we cannot update Drupal 8 to optionally allow Twig 2 support, even though the API is fully ready for that. So these changes can only be made currently in your Drupal 9 environment.
- Use Upgrade Status either on the UI or via Drush to check your Twig files for deprecated syntax use.
-
Twig updated from 2.x to 3.x (Drupal.org)
- Note especially changes to
spaceless
syntax and the removal of support forif
inside afor
clause.
- Note especially changes to
-
Deprecated features in Twig 2.x (twig.symfony.com)
- This page from Twig's official documentation lists all of the deprecated features in Twig 2.x which were removed in Twig 3.x.