DrupalX

Extension
Framework

Introduction to DrupalX's Twig extension

What's great about Twig

Drupal 8 (in contrast to Drupal 7) is intentionally using a new concept for its HTML  templates: The template language "Twig". This has many advantages over Drupal 7 where you created templates simply in PHP. First and foremost, there is the increased security: Errors in a template can not quickly lead to massive security holes, because a dedicated template language like Twig has only very restricted access to the system. For example, it's not possible to write files from Twig etc. A next advantage is, that a language optimized for templates can often be much shorter and more simple than PHP could be in a similar situation. And, as you've learned, we like simplicity and brevity. You'll find more information about the advantages of twig on their homepage under the section "Why yet another template engine?".

As a final - and probably the most important - argument for using Twig we'd like to mention the increased code quality. With the clear distinction between PHP and Twig it's much easier to really ensure a strict separation of code that's just preparing and rendering stuff for output and code that actually processes/modifies things. An existing template, for example, cannot accidentally turn into a mess where it also writes to the database or creates any files - simply because Twig doesn't offer those functions in the first place.

What's not so great about Twig and why we are extending it

If it is, however, an advantage, that Twig only provides a reduced set of functions, isn't it counter-productive if DrupalX extends Twig again to give it more features? Yes and no: DrupalX strictly only extends features that dont change any data (database, files). Only read-only functionality which is concerned with the preparation of output or any methods that help decide what to render, is provided.

The basic (and advantageous) principle of separation of rendering and modification is still upheld. DrupalX is extending Twig only to allow reacting in a more flexible way to complex rendering demands. Sometimes you don't want to output some element on your page - e.g. a menu or a view - exactly like it's normally rendered by Drupal. Of course you can use preprocess hooks etc. in PHP, but actually this is what actually violates the separation of rendering code and modifying code. It's sad that the powerful Twig language cannot be used as soon as demand gets only a little bit more complex.

Fortunately, Twig is easily extendable, and DrupalX makes heavy use of this feature: We're extending Twig to the max and make it way more powerful that you are used to. DrupalX has you covered even for rather obscure rendering demands.