Theming in Drupal 8 - Conversion of themes to Twig

This post adds to the successful and popular "Theming in Drupal 8 with Twig?" (Part 1, Part 2) series from Steffen. It deals with converting Drupal phptemplate themes to use the new Twig template engine, like we recently did with our Busy theme. This is all for Drupal 8, so this might not be helpful to you just yet, but if you wanna get a headstart on converting your phptemplate theme to Twig, nothing's holding you back from starting right now! If you don't know how to get your Drupal 7 theme to Drupal 8, there's an older write-up on how to convert a Drupal 7 theme to Drupal 8 in our blog (keep in mind that things in Drupal 8 change rapidly so some of that text might already be outdated).

First of all, Drupal 8 has Twig as its default template engine. That means if you don't write any other setting into the, Drupal will use Twig as its template engine. So, if the current theme is based on phptemplate, you must delete the line "engine: phptemplate" from your In the following example it's line #5.   [gist:5865857]

After that you can start with the "real" rebuilding. Make sure you know the basic syntax and features of Twig.

Copy the template file and rename it from TEMPLATE_NAME.tpl.php to TEMPLATE_NAME.html.twig. Then you have to look at each line and replace PHP commands with Twig commands. The following example shows you such a conversion of a template file:


Similar conversions have to be applied to arrays and loops.

[gist:5866312] [gist:5866317]

If you like to save some time, there is a nice Drupal 7 module called Twigify (sandbox-project). It tries to convert your theme automatically from a phptemplate theme to a new Drupal 8 Twig based theme. But keep in mind: complex code still needs to be edited manually.

So, don't be afraid of converting your themes to use the Twig template engine, it isn't that hard.