Drupal 8 Adopts Twig Templates

Drupal has revamped its template engine for Drupal 8 with Twig replacing PHPTemplate. PHPTemplate had been Drupal’s template engine for over a decade and this switch represents Drupal’s biggest change to their frontend architecture since 2005. Twig was created by Fabien Potencier, the creator of the Symfony framework, and its improved functionality and security has been accepted and adopted by Drupal’s newest iteration with open arms. The choice to adopt Twig highlights Drupal 8’s motivation to adapt and adopt a modern, powerful, OOP-based engine that is in line with the Symfony initiative.


More Concise

Making the change from PHPTemplate to Twig enabled Drupal 8 to improve its performance by compiling a project’s template files into raw PHP code for easier parsing. Twig’s syntax is more concise than PHP, which makes the language easier to compile and easier to read. Not only do Twig template files look cleaner than its predecessor’s, but they also further separate a website’s logic from its presentation.


More Modularity

Twig, unlike its predecessor, empowers developers to inherit, or extend, template files from inside of other template files. This modularity allows developers to create smarter template structures that reduce the need for writing, and loading, duplicate code. By simply extending an existing template {% extends ‘template.html.twig’ %} a developer can manage any aspect of the original file through the use of Twig blocks. Blocks are used throughout Twig templates to define portions of a file that can be modified by child (more granular) templates. Twig’s ability to extend itself through the use of blocks provides developers better tools to define their project structure in Drupal 8.


More Security

The inclusion of Twig in Drupal 8 also means the CMS is more secure. The Twig library has been fully tested and vetted by the community and it is ready to be used within enterprise applications or websites. In addition to passing its unit tests, Twig has excellent features to keep your developments secure, like autoescaping. Autoescaping ensures that unsanitized output won’t be encountered in Drupal 8, unlike previous versions of Drupal and the PHPTemplate engine. Twig also prevents functions from executing if it determines them to be unsafe, making the frontend of your Drupal 8 website as secure as it can be.


The inclusion of Twig in Drupal 8 represents a major overhaul in the content management system’s structure. However, with an understanding of the new template engine’s benefits, it is easy to understand why this overhaul was necessary. With any luck, Twig will be structuring and securing new Drupal sites for a decade or more!