Subscribe for expert
tips and access news

An intro to the Twig templating engine in Drupal 8

Michael Chadwick   —   2 October 2015   —   Code & Drupal

An intro to the Twig templating engine in Drupal 8

Having worked with Drupal for a little over a year now, I understand how learning something new can take time and patience. So, when Drupal 8 drops developers will need to wrap their heads around some brand new concepts and put them into practise as quickly as possible.

One of the most noticeable changes will be to Drupal’s templating engine. No longer will PHPTemplate, the engine built for Drupal developers by Adrian Rossouw, power our templates. His aim with PHPTemplate was simple; to build a new templating system for Drupal, which enabled flexibility and reduced complexity. Building on Adrian’s goals, the Drupal 8 community has pushed for a fast, more secure and flexible driven templating engine: Twig.

So what is Twig and why the change?

Twig is a modern PHP templating engine built by the team at SensioLabs, who also created the PHP framework Symfony 2.

3 big reasons why Twig is a great addition to Drupal 8:

  • It’s Fast - The PHP output Twig produces is optimised and will reduce your site’s PHP overhead.
  • It’s Secure - Twig makes it a lot easier to write secure markup with the likes of simple manual and automatic HTML escaping. Twig also has a sandbox extension which helps you evaluate untrusted code.
  • It’s Flexible - Twig also allows you as the developer to define your own custom tags and filters due to its flexible lexer and parser.

Let’s have a deeper look into Twig within the context of Drupal.

Twig File Naming Conventions for Drupal.

The way we will override a Drupal template has not really changed. All we need to do is remember the new file extension which comes from Twig. The naming convention for all theme templates has changed from *.tpl.php to *.html.twig.  Simple!

HTML template

  • Base template: html.html.twig

Page template

  • Pattern: page--[front|internal/path].html.twig
  • Base template: page.html.twig

Regions

  • Pattern: region--[region].html.twig
  • Base template: region.html.twig

These conventions continue on for all manner of core entity types in Drupal. See more details of the naming conventions on Drupal.org.

Templating in Twig

One thing I look forward to when using Twig will be the cleaner markup it outputs. For me, a cleaner template file will be easier to work with and maintain. Looking at the Page template file pulled from the new Drupal 8 Bartik theme which uses Twig (core/themes/bartik/templates/page.html.twig), the first thing you will notice is the use of curly braces to define a code block. There are two kinds of these code blocks, the first one is a printing code block. This is denoted by the use of double curly braces, and will allow you to print variables to the template.

1
{{ }}

The second kind of code block is the functional code block. This is represented with two percentage symbols wrapped in curly braces. The functional code block  is used to execute statements such as an if statement or a for-loop.

1
{% %}

An example of this would be to render the logo from your page.html.twig file. We first need to check the logo is set using a conditional block and then render it.

1
2
3
{% if logo %}
  <img src="{{ logo }}" alt="{{ 'Home'|t }}" />
{% endif %}

To break this down, we first open up a logic code block. In this case an ‘if statement’ that checks for the logo is used and when the condition is met it prints the <img/> tag. Within the src attribute, we use the rendering code block to render the logo’s image url. We also use the rendering code block to print the alt attribute text for the image. The use of ‘|t’ would be the same as using the t() function, to allow translation by Drupal.

Already by removing a lot of the bloat that comes with PHP templating, which Drupal 7 uses, we can see how Twig will enable us to write cleaner and more maintainable code. I am very excited at this prospect because at the end of the day we have to create, edit and manage this code and the cleaner it is the better it is to work with.

Debugging Twig

Twig in line with Drupal comes with some great features, making it easier to find and squash those pesky bugs during development. By default Twig’s debug mode is turned off, therefore you have to enable it in your Drupal settings. To do this simply navigate to your services.yml file (sites/default/services.yml) where the setting is well documented and looks like;

1
2
3
parameters:
  twig.config:
    debug: true #originally false

One of the biggest reasons for enabling debug is because Twig will compile into PHP, and then store that PHP in memory. This is a problem when you are constantly updating files during development. You can clear the Twig cache but doing this all the time will become tedious. This is where Twig Auto-load can help, by enabling it in your settings, it will do the job for you. Again this is by default set to false and needs to be enabled. You will find it further down in the services.yml file.

Examining variables on the page is also a simple task. By using the dump() function you are able to pass the name of the variable and it will print it to the screen, similar to what the Devel module would offer you with dpm(). Except this time it is all baked into core!

1
{{ dump(title) }}

Summary

In summary the Twig templating engine will be a breath of fresh air to themers and developers. Cleaner and more secure code will promote good practice and enable us to produce better work. I know I’m looking forward to the change, what do you think? Let me know in the comments.

Also as a disclaimer. With Drupal 8 still in development and as of writing this, has only a few criticals remaining in its Critical Countdown, things could still change. I would recommend keeping a close eye on the Drupal documentation which is kept well up to date.



Our Partners / Accreditations / Networks

0161 872 3455

Sign up to our newsletter