Twig in Drupal 8. Working with Twig templates

Drupal 8 surprises us by its new features. Instead of our custom PHP Template, we will use the Twig Template. That is, if we used templates *.tpl.php before, then we will now use *.html.twig files.

Twig - is a compilation handler of open source templates, written in PHP programming language.

Let's look at what are the benefits of Twig:

One of the main advantages - is the speed. Users prefer fast loading sites, which allow the user to quickly find the information they need. Twig compiles templates into PHP code to achieve one of their goals - the most optimal speed. Great importance for the success of the project is the rapid development of the site.

Another important advantage of Twig - is the ripeness. It is in comparison with PHP Twig has a shorter and more convenient syntax. With it, templates become easy to read. The syntax helps web designers perform their work quickly and efficiently. Concerning compilation, the syntax of Twig is clearer and easier, which makes it possible to construct better also efficient templates. Twig syntax - is very similar to HTML syntax.

Another argument in favor of Twig – extensibility. Twig has an open architecture and is very rubbery. Due to this, you will be able to fulfill all your needs of any degree of complexity. For example, add new features, tags, keywords, syntax, filters, etc. The expansion option allows developers to use the tools they like the most to create a better project structure in Drupal 8. Twig can also add it own extensions, if needed.

Safety is equally important. Since security is a very important factor not only in the very development of the site, but also in its further existence - the potential of Twig is just to provide us with this. With regard to security, it is possible to highlight such features of Twig as "sandbox" and HTML escaping. “Sandbox”: Twig can be used for applications as a template language that allows users to independently change their design. The developer himself can define a set of filters, methods and tags and limit their number. "Sandbox" can be used for both individual and all templates of your choice. Twig is characterized by the feature itself to find and automatically remove any unreliable code of the template. It is precisely in terms of security that you can use auto-deduction for individual parts of the code or entire HTML template. Also, I want to point out that you can use the tried and true Twig stable library when creating a variety of projects.

Compared to some other language templates, Twig features its most powerful part - the imitation of templates. Now you do not have to do the job of copying the parent templates. After introducing Twig, you can create a layout markup that will be basic, and then redefine or expand any block that needs to be replaced.
So, we looked at a number of Twig capabilities that will greatly speed up the creation of your Drupal 8 site.

Let's summarize the benefits of Twig:

        • the best speed;
        • compressed and more convenient syntax;
        • extensibility;
        • security;
        • imitation templates.

In its arsenal, Twig also contains a list of filters and tags that are available by default. The registration process itself is easy and you are not waiting for the difficulty of creating a new server, which you can easily add the tag twig.extension. Since Twig supports various functions, you can easily add any other ones you want. The Twig system itself was most likely designed for presentations, not for programming, so simple Twig templates do not handle PHP tags.

Caching Templates in Twig

We already know that Twig is fast. When starting, we will see that the Twig templates are compiled to the original PHP class. Then these classes are located in the directory app/cache/{environment}/twig. They will be useful in debugging. When programming, you can make corrections to the Twig template when debug mode (dev environment) is enabled. At that time, the template will be automatically recombined every time and you see all the changes immediately.

When debug mode is turned on (usually for the prod environment), to see all the changes in the Twig templates, unfortunately you will be forced to clean the cache directory yourself.

Often there are common elements in the templates of the same project (sidebars, headers, blocks). Classes in PHP work in this direction - one template can decorate another. So we can make a basic layout, which will contain all the common elements of your site. In the base template, you can redefine the blocks, expand markup.
Base.html.twig will be useful in determining the parent template.

Work with template imitation:

        • The base pattern must have many tags {% block %}. The more blocks, 
          the more flexible markup;
        • Use the {{ parent() }} function to get content from the parent template 
          block. In order not to override the full content of the parent block, 
          you can add only the necessary information using this feature;
        • The {% extends %} tag must be the first among a number of other template 
          tags if used;
        • If you see that the data in the patterns is repeated, then you need to 
          move the duplicate content to the {% block %} parent template. Sometimes 
          the best option will be to transfer content to a new template.

Placement of templates

There are two locations for default templates:
        • app/Resources/views/

        • path/to/package/resources/views/

Basic and general templates can be found in the views directory. Most templates are located in the app/Resources/views/directory.
In the Resources/views/ directory and its sub directories, there are templates for the secondary package.

Twig Filters

The great feature and advantage of Twig is the availability of simple and useful filters. Let's take a look at these filters, for example: To return the absolute value used abs:

   { # number = -5 # }

   {{ number|abs }}

   { # outputs 5 # }

To return the value of the variable shape in capital letters:

   {{ shape | upper }}

To transform the first character to the upper case, and all others to the bottom apply capitalize:

   {{ 'twig in Drupal 8' | capitalize }}

Json_encode - is used to return JSON data views. First use to return the first element of the array or string. To translate the value to lowercase - lower.

You can combine filters as needed. A filter that cuts the gaps in the beginning and the end of the value of the variable:

   {{ shape | upper | trim }}

You can use filters on an entire block. For example, to transfer everything within the block to uppercase:

   {% filter upper %}

This box is {{ shape }}.

   {% endfilter %}

There are filters that accept arguments. Among them is date to specify the format in which the date variable will be displayed.
We have become acquainted with only a part of the filters, and in general, Twig offers us a large number of practical filters.
Twig can use different control structures, since for each template file there is an important loop or statement if/else. Operator if/else:

   {% if shape is defined %}

   {{ shape }}

   {% endif %}

Differences between Twig and PHP

The main differences between Twig and PHP are:

        • operator If;
        • output of a variable;
        • creating an array;
        • providing variable values;
        • cycles.

In this article, we became familiar with Twig, its benefits and capabilities. Also reviewed some types of filters and differences between Twig from PHP. Usually this is just part of the features of Twig files. When you work with the template, you can read more about Twig's features and functions.

Quick Free Quote
We respect your privacy. NO SPAM No selling your personal data.
We will respond to your query & collect further details within 24 hours. Guaranteed!


We are friendly people who love to talk. So go ahead and contact us.


Awards & Certification