Twig PHP Templating Language

Drupal 8 is packed with many changes and new enhancements geared towards optimization, functioning, and standardization. Finally, after years of working within a hybrid surroundings, nosotros are now truly moving towards a system that separates logic, beliefs, and design. In this blog, I will get over some of the changes in Drupal's theming layer that have gone from the wild, "cowboy-like" PHP template, to a more simplified and standardized templating system called Twig.

What is Twig?

Twig is the new templating engine for Drupal 8, which uses a different language and syntax than prior Drupal php templates used for theming and rendering output to a site page. Twig templates compile markup downward to plain optimized PHP versus regular unoptimized PHP, thus enhancing speed and performance.

Why Twig?

The nifty advantages of using Twig is that it is fast, modernistic, and secure. Information technology has been developed for use with Symfony, which is the new PHP framework backside Drupal 8 that follows the MVC (model-view-controller) architecture.

Not only is Twig a faster templating system than the PHP templates used in prior versions of Drupal, it as well easy to learn. It provides clear error messaging and is besides very well documented.

Twig too provides consistent theming practices that can be taken up by other developers and site themers every bit projects get handed off from one evolution visitor (dev team) to another, equally many often do. The manner Twig is structured it decreases the possibilities for broad differences in coding and theming practices, techniques, non-standard coding, and hacks oftentimes seen when working with prior versions of Drupal, where sites take been adult and maintained by other people and teams. Standardized consistency is a key reward to Twig'southward efficiency.

Twig Syntax

At that place are some key differences in syntax and coding standards when working with Twig versus the PHP templating system of prior Drupal versions. I won't go into all of the differences that exist in this blog, but I will highlight a few examples to provide a general agreement or "bird's centre view" and so-to-speak.

Open up and Closing Tags

In PHP templates prior to Drupal 8, we used open and closing tags as shown below:

                      <?php         /**           * Some file comment…         */     ?>        

In Twig, we open and shut our template code as follows:

                      {#         /**           * Some file comment…         */     #}        

Template File Naming Conventions

When assigning file names to our PHP templates prior to Drupal 8 (Drupal 7 for case) nosotros used a naming convention as follows:

node–webform.tpl.php

In Drupal 8 with the Twig template naming convention nosotros will use this instead:

node–webform.html.twig

Function Naming Conventions

When declaring function names in PHP templates prior to Drupal 8 we used the following convention:

theme_node_links()

In Drupal 8, using the Twig template system we will utilise the following:

node-links.html.twig

Press Variables

In prior versions of Drupal we would output a variable in the post-obit manner:

                      <div class="content">         <?php impress $content; ?>     </div>        

In Drupal eight using Twig, we volition instead output the variable like this:

                      <div class="content">         {{ content }}      </div>        

Assigning Variables

To assign a variable using the prior PHP template of older Drupal versions, we would do something like the following:

                      <?php         $myVar = $content->comments;      ?>        

With Twig templates we instead do this:

                      {%         set myVar = content.comments     %}        

Printing Hash Central Items

In the PHP templates nosotros printed hash key items equally follows:

                      <?php         impress $item['#detail']['alt'];     ?>        

In Twig templates will instead print hash central items like this:

                      {{         item['#item'].alt     }}        

Assigning an Assortment

Prior to Drupal 8, nosotros would assign an array inside the PHP template such every bit this:

                      <?php         $args = assortment('!author' -> $author, '!date' -> $created);     ?>        

In Drupal 8 using Twig, we volition assign an array as follows:

                      {%         gear up args = {'!writer':author, '!date':created}     %}        

Conditionals

Using PHP templates we would setup a provisional statement like this:

                      <?php         if($content->comments):             /* run some code… */         endif;     ?>        

With Twig templates we setup the conditional similar this instead:

                      {%         if content.comments     %}             /* run some lawmaking… */     {%         endif     %}        

Command Structures

Prior to Drupal 8 using PHP templates we would setup a control structure equally follows:

                      <?php         foreach($users as $user) {             /* run code… */         };     ?>        

In the Twig template nosotros do the following to setup a command structure:

                      {%         for user in users     %}         /* practice something… */     {%          endfor     %}        

Translate ('t' function)

Prior to Drupal eight within the PHP template, to translate a string of text we would do the following:

                      <?php         print t("Howdy World");     ?>        

In Drupal 8 using Twig we instead do this to translate a string of text:

                      {{         "Hello World"|t     }}        

Other Examples of Syntax Differences

For more examples of Twig syntax see the Twig Documentation.

Exposing Variables in a Twig Template

While most common variables will exist documented within a Twig template, in that location volition exist a need to expose additional variables inside the scope of a Twig template such as those provided by modules.

Debugging:

To expose the variables available to a Twig template, debugging must first be enabled in order to output the variables for viewing. To enable debugging in Twig yous'll demand to prepare the debug parameter to "true" within the "twig.config" department of the Drupal viii YML file. This file is located inside "yoursite.com/sites/default/services.yml". Find the "twig.config" parameters and set "debug" to "true".

Example:

parameters:
twig.config:
debug:true

Note: This is extremely useful for development purposes, just be sure to change the "debug" parameter back to "imitation" when migrating and using this YML file on a product site.

An advantage of using Twig debugging is that the markup of the Twig template is surrounded by HTML comments containing theming data like template file suggestions, similar to using the Theme Developer contrib module in Drupal 7.

Some other reward of Twig debugging is that the templates are automatically recompiled whenever a change in code is detected. This is achieved past by setting the "auto_reload" parameter to "truthful" within the YML file located at "yoursite.com/sites/default/services.yml". Every bit with the twig debug parameter, this as well should exist prepare back to "false" when migrating or using on a production site.

Outputting Variables – Using the "dump()" Office

To display variables available to a Twig template use the dump() function. To output all variables within the telescopic of a Twig template, simply use the dump() function with an empty parameter such as this:

                      {{         dump()     }}        

This is similar to using the " " function within the PHP theme template of prior Drupal versions.

If you know the particular variable you wish to output for inspection, you lot can utilize the dump() function including the variable proper name as a parameter within your Twig template similar this:

                      {{         dump(author)     }}        

This is similar using "<?php print_r($author); ?>" in prior versions of Drupal using PHP templates.

Markup in Drupal 8 (HTML5 & CSS)

HTML in Drupal 8

In regards to HTML markup in Drupal 8, a key difference now is that the doctype has evolved from XHTML to HTML5. Nosotros at present accept the ability to leverage syntactic tags such as: <audio>, <video>, and <canvas>, with the addition of SVG (scaleable vector graphic) support. This allows the the template to output multimedia and graphic content without the demand for third political party plugins and APIs. More importantly, HTML5 provides universal folio elements common for theming such as: <commodity>, <header>, <footer>, <nav>, <department>, etc., which besides enhances the semantic relevance of the page'due south content.

CSS in Drupal 8

CSS in Drupal eight has become much cleaner containing fewer selector IDs with simplified and more intuitive class names than prior versions. There is now less nesting from excessive divs, less code, and thus the markup as a whole is far more optimized and better geared towards performance.

Drupal 7 CSS Class Instance:
          <torso class="html front not-logged-in 1-sidebar sidebar-first page-node">        
Drupal 8 CSS Class Example:
          <body class=" ">        

In Drupal 8, CSS structure and file naming conventions are based on SMACSS, which is a method for writing CSS that is both scalable and modular. SMACSS is a style of structuring CSS to add flexibility and ameliorate maintainability as a project grows and is shared amid multiple themers and/or handed off from one development team to another.

Theme Structure in Drupal 8

Basically, the structure of the theme'south page is the same as within Drupal 7. Hither you take the "html", "page", "region", "block", "node", and "field" layers, which brand upwardly the whole structure of a page and template files for each deport a similar naming convention except for ".html.twig" suffix required for the Drupal 8 template names.

Theme Template Name Examples:

a) Html.html.twig
b) Page.html.twig
c) Region.html.twig
d) Block.html.twig
e) Node.html.twig
f) field.html.twig

Encounter a visual representation of the theme'south structure layers here:
http://mortendk.github.io/drupal8-twig-frankfurt-2014/images/pagebuild.png

Drupal 8's Theme .info File

The .info for the theming layer within Drupal 8 is somewhat similar to Drupal vii, still there are a some significant differences. First of all, the .info file is now in YML and requires the ".yml" file name suffix. Ex: "mythemename.info.yml". Another cardinal departure is how the stylesheets and regions parameters are alleged. Also, stylesheets are now called and named per the SMACSS convention as referenced higher up. Below is a comparison of a theme's .info file in Drupal 7 versus Drupal viii.

Drupal vii theme.info Case:

                  

Drupal 8 theme.info.yml Example:

          name: Bartik type: theme description: 'A flexible, recolorable theme with many regions and a responsive, mobile-outset layout.' package: Core version: VERSION core: viii.ten  stylesheets: all: – css/layout.css – css/way.css – css/colors.css print: – css/print.css ckeditor_stylesheets: – css/ckeditor-iframe.css remove: – sites/all/modules/somecontrib/style.css  regions: header: Header help: Help page_top: 'Folio top' page_bottom: 'Folio bottom' highlighted: Highlighted featured: Featured content: Content        

Excluding Unwanted Stylesheets via "remove:"

In the Drupal eight .info.yml case shown above, notice the "remove:" that is now bachelor to use. This is quite handy because equally you know Drupal has a nasty addiction of loading an excessive number of stylesheets when in that location is a heavy use of numerous contrib modules in a site. Earlier themers had to live with this and create many CSS overrides in their theme'due south custom CSS file in order to piece of work around and override the style rules coming from all of those unwanted and often unneeded stylesheets. At present in Drupal eight, we have the "remove:" option available to united states to quickly and easily exclude any particular stylesheet(s) we do not desire to load into our theme. Not merely does this alleviate the themer's workload, but also provides another means to raise the site's loading performance. Loading fewer stylesheets will increase the speed in which the site and the site's pages brandish for the end user.

Practice You Still Need to Apply a PHP-based Template Engine with Drupal eight?

Are you 1 of those cowboy rebels, or a person who is bull-headedly resistant to change, and absolutely accept to pause the new theming convention to employ PHP inside your templates rather than use Twig? If so, Drupal 8 does provide an option for doing that. You can simply add together the "engine:" parameter to your .info.yml file to override Twig entirely and fallback to PHP as shown in the case below.

Switching Drupal viii Theme from Twig to PHP Example:

engine: phptemplate

Want help with your project? Contact u.s..

Outputting Regions to a Page in Drupal eight

In Drupal 8, the ability to display regions within a page template has gotten easier in terms of coding. The basic principle is substantially the same, even so the syntax and markup used in Twig is a bit less and more simplified. Below is an example of how a region is displayed in a Drupal 7 PHP template compared to a Drupal 8 Twig template.

Drupal 7 Method for Displaying a Region Case:

                      <?php if($page['footer']); ?>         <div id="footer">                      </div>     <?php endif; ?>        

Drupal 8 Method for Displaying a Region Example:

                      {% if page.footer %}         <div id="footer">             {{ folio.footer }}         </div>     {% endif %}        

Summary

Of course there are many more specifics and differences that can exist covered between Drupal 8 and theming with Twig versus older versions of Drupal. However, this blog should serve well in highlighting the wide telescopic of differences and basic usage of working with the new Twig templating system. The key takeaways here are that Drupal 8 has moved to a more efficient and optimized style of rendering a site's theme through the use of Twig. Drupal viii has come far in separating design from functionality and and so sites will exist more optimized and improve tuned for functioning, in add-on to lifting some of the redundant and formerly heavy workload previously required of themers. Of course in that location is a learning bend as with any change in technology, but once the basic concepts are understood all else should fall into identify rather quickly.

Resources

  • Twig by Sensio Labs: http://twig.sensiolabs.org/
  • Drupal viii: https://www.drupal.org/node/2563023
  • Symfony PHP: https://symfony.com/
  • MVC Architecture: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%fourscore%93controller
  • Twig Documentation: http://twig.sensiolabs.org/documentation
  • Twig Coding Standards: http://twig.sensiolabs.org/doc/coding_standards.html
  • Twig Debugging: http://twig.sensiolabs.org/dr./functions/dump.html
  • Theme Programmer Contrib Module: https://www.drupal.org/projection/devel_themer
  • Using "print_r()" Function: http://php.net/transmission/es/office.print-r.php
  • XHTML Reference : http://xhtml.com/en/xhtml/reference/
  • HTML5 Reference: http://world wide web.w3.org/TR/html5/
  • SVG Reference: http://www.w3.org/Graphics/SVG/About.html
  • Drupal 8 CSS Architecture: https://www.drupal.org/coding-standards/css/architecture
  • SMACSS: https://smacss.com/
  • Drupal viii Theming Structure (visual reference): http://mortendk.github.io/drupal8-twig-frankfurt-2014/images/pagebuild.png
  • Drupal 8 Theming Intro to Twig: https://www.youtube.com/watch?five=QCKHvJWgdFs
  • Theming in Drupal eight TWIG Morten DK: https://world wide web.youtube.com/picket?v=GRldYinpkcE
  • Theming Drupal 8: https://www.drupal.org/theme-guide/8
  • Twig in Drupal 8: https://www.drupal.org/theme-guide/8/twig