Drupal 8 + Twig: More Secure, More Power

  • 4 minute read

Originally posted by our partner, Genuine.

With PHPTemplate engine, Drupal took aim at following MVC best practices: Let’s separate the logic from the presentation layer. In line with the adoption of Symfony 2, Drupal 8 will replace PHPTemplate with Twig and take this philosophy one step further.

Why Twig? It’s more secure.

In Drupal 7, user-submitted text needed to be sanitized with check_plain() in order to prevent the most common web vulnerability, Cross Site Scripting (XSS). If a themer forgot to sanitize their output there would be a security hole. Autoescaping was recently accepted into Drupal 8, which removed this concern all together. PHP functions will also be stripped from templates and this goes in line with separation of concerns. Instead, you’ll have concise, clean markup such as:

Old:

<?php print render($content); ?> 

New:

{{ content }} 

With the new syntax, you get clean templates, clear separation of logic and presentation, and more security. A number of other benefits to using Twig are highlighted in OSTraining’s blog, including one specific benefit I want to point out, which is the idea behind inheritance.

Inheritance

“The most powerful part of Twig is template inheritance” – Sensiolabs

Drupal 8 + Twig integration eliminates the need for copying and pasting base or parent theme template files into your custom templates. Similarly to how Sass and Less simplifies your CSS workflow with the @extend directive, Twig will drastically cut down the amount of template files and code you need to organize your theme.

{% extends "themes/sub_bartik/templates/node.html.twig" %} 

This is similar to PHP’s “include function” that allows you to create dynamic, hookable templates. However, there’s a huge leap forward in templating that I’m about to show you: Twig blocks (not to be confused with Drupal blocks).

From Steve Persch’s Bartik’s theme inplementation to display a node in Drupal 8:

Parent file:

{# This empty block allows child templates to insert markup into this
   place in the header without re-writing the entire template. #}

{% block header_fields %}
{% endblock %} 

New file:

{# Override the header_fields block to put field_image there because
   this site needs it there. #}

{% block header_fields %}
  {{ content.field_image }}
{% endblock %} 

It will be very interesting to see what kind of conventions will emerge from the use of Twig blocks. Much like the adoption of Sass, Twig will prove to be both a win and a challenge for development teams to adopt and scale their workflows.

Alex Vallejo is a junior web applications engineer at Genuine who works with Drupal for clients in the B2B industry. Vallejo’s career began as a financial analyst and in 2011 began working with WordPress and PHP, then moving to Drupal in 2013.