Why twig in drupal 8

Why twig in drupal 8 DEFAULT

Subscribe to our blogs

What is Twig?

Twig is a faster, and more secure template system than PHP. Twig is brought by a wider PHP world. Twig was built  by SensioLabs, the creator of Symfony2 framework. Drupal 8 is using Symfony2 to overhaul its codebase. Twig was the right choice to use for Drupal themes.

Using Twig in Drupal

Twig is the default templating engine in Drupal 8.

One of the results of this change is that all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced in by *.html.twig template files.

Comparison of PHP template & Twig theming

1. Docblock

PHP Template


File Names

PHP Template file : node--article.tpl.php
Twig file : node--article.html.twig
PHP Template function : page.tpl.php
Twig file : page.html.twig


You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

Printing a variable

PHP Template


Printing a hash key item

PHP Template


Assigning a variable

PHP Template


Assigning an array

PHP Template


Setting Variables

You can assign values to variables inside code blocks.












PHP Template



PHP Template


Implode a list

PHP Template

Original Twig:

Drupal 8 Twig:

How to enable debugging?

  1. Locate your site's services.yml file, likely located in sites/default/services.yml
  2. Edit the services.yml file and enable one or more of the debugging options defined below.


    debug: true


The dump function dumps information about a template variable. This is mostly useful to debug a template that does not behave as expected by introspecting its variables:

In an HTML context, wrap the output with a pre tag to make it easier to read:


Determine whether a variable is empty:

{# evaluates to true if the user variable is null, false, an empty array, or the empty string #}

Advantage of using Twig

Concise: The PHP language is verbose and becomes ridiculously verbose when it comes to output escaping:

Template oriented syntax

Twig has shortcuts for common patterns, like having a default text displayed when you iterate over an empty array:

Full featured

Twig supports everything you need to build powerful templates with ease such as multiple inheritance, blocks, automatic output-escaping, and much more:


Functions can be called to generate content. Functions are called by their name followed by parentheses (()) and may have arguments.

For instance, the range function returns a list containing an arithmetic progression of integers:

Twig: Fast Template

Using Twig will accelerate the performance in Drupal 8. In order to achieve the best speed possible and save time during Drupal development, Twig compiles templates down to plain optimized PHP code.

The overhead compared to regular PHP code was reduced to the very minimum.

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elseif/else), for-loops, as well as things like blocks. Control structures appear inside {% ... %} blocks.

For example, to display a list of users provided in a variable called users, use the following tag:



The if tag can be used to test an expression:


To comment-out part of a line in a template, use the comment syntax {# ... #}. This is useful for debugging or to add information for other template designers or yourself:

Sours: https://www.anubavam.com/blogs/how-use-twig-template-engine-drupal-8

Twig is a template engine for PHP, which is the language used in Drupal. Twig can be used for templates in generic PHP applications as well as Drupal 8 themes. The Drupal implementation of Twig is the same as regular Twig with a couple of Drupal additions. Drupal adds some custom filters and automatically handles the render pipeline for you. Anything you can do in regular Twig you can also do in Drupal's implementation of Twig.

Example tasks

  • Customize markup in templates for a Drupal 8 site
  • Use dynamic data from variables within template files
  • Customize markup in PHP applications that use Twig for templates


Resources on this page use both generic PHP applications as well as template files from Drupal 8 themes for context and examples. The Twig that is used in generic PHP applications can be used in Drupal templates as well. Note that Drupal has extended Twig and provides some Drupal-specific filters and functions. In some cases, these Drupal-specific functions or filters are preferable to their generic Twig counterparts.

Note that Drupal 8 currently uses Twig version 1.x, while Drupal 8.4 is slated to use Twig version 2.x (issue here). Some Twig features differ between these versions.

Drupalize.Me resources

Related tutorials

Using Twig's function, you can attach asset libraries of CSS or JavaScript files. Learn more about asset libraries, or jump straight to the relevant section on in Attach a Library.

Sours: https://drupalize.me/topic/twig
  1. Townhomes for sale peoria il
  2. Point of sale terminal market
  3. Otg support software for samsung

Join today and get access to 1,000's of books and videos. Learn WordPress, Drupal, Magento, Joomla and more! Sign up today!

twigPHPTemplate is the engine that has been driving Drupal templates since 2005.

After nearly 10 years of honorable service, PHPTemplate is about to be replaced by Twig in Drupal 8.

This will be the biggest overhaul of Drupal theming in a decade.

What is Twig? How will it change Drupal themes? Read on and find out ...

What is Twig?

Twig is a template framework and is a direct replacement for PHPTemplate. 

Unlike PHPTemplate which was developed in-house by Drupal developers, Twig comes from the wider PHP world.

Twig was created created by SensioLabs, the same people who develop the Symfony2 framework. Drupal 8 is using Symfony2 to overhaul its codebase. Because Twig is natively supported by Symfony2, it was a logical choice to use for Drupal themes.

You can find the Twig website at http://twig.sensiolabs.org.

Who uses Twig?

Except for Drupal 8, it's not a very distinguished list yet:

Without a doubt, Drupal 8 will be by far the largest platform using Twig.

Is there any Twig documentation?

However, as you saw above, there aren't too many people using Twig yet. There are no books available and there's currently a shortage of online tutorials. I suspect that will start to change when Drupal 8 arrives.

How has Twig changed Drupal 8 themes?

Maybe it would be easier to answer that question in reverse ... how has Twig not changed Drupal 8 themes?

Let's compare two snippets from Bartik in Drupal 7 and 8. These snippets have an identical function.

This is Drupal 7 and the node.tpl.php file:

This is Drupal 8 and the new node.html.twig file:

The only things that haven't changed in those snippets are the H2 and a tags.

Compare the two side-by-side:

  • <?php print $title_attributes; ?> has been replaced by {{ title_attributes }}
  • <?php print $node_url; ?> has been replaced by {{ node_url }}
  • <?php print render($title_suffix); ?> has been replaced by {{ title_suffix }}

Looking at it that way, it's fair to say that Twig has produced much more readable code than the PHP did.

Why Twig in Drupal 8? #1. Syntax

The five following point are all shamelessly plagiarized from Jen Lampton, who leads the Twig project. She's given a whole series of presentations on Twig in Drupal. 

Jen outlines 5 pain points with Drupal 7 themes. The first is syntax.

Drupal 7 mixes up data types including strings, objects and arrays. It also has multiple different ways of printing variables such as $node->nid and then $node_url.

Drupal 8 will access all variables consistently, for example {{ node.nid }} and {{ node_url }}

Why Twig in Drupal 8? #2. Inconsistency

Sometimes Drupal 7 relies on template files, other times it relies on functions. This can make it hard to understand how to override some parts of the Drupal core.

Drupal 8 only uses template files.

Why Twig in Drupal 8? #3. Complexity

Jen produced two images to illustrate how much simpler Drupal 8's theme system will be.

Here's Drupal 7:


Why Twig in Drupal 8? #4. Redundancy

There's a lot of duplicated code in Drupal 7 themes.

Drupal 7 would have multiple files with the same lines of code, including:

Drupal 8 uses lines like this: {% extends "node.html.twig" %}. This means you can use proper inheritance inside your theme files and eliminate a lot of duplicate code.

Why Twig in Drupal 8? #5. Security

Drupal 7 would often print out unsanitized data. You could even run database queries from directly inside the theme files.

Drupal 8 can automatically sanitize variables and won't permit unsafe functions to run.

About the author

Steve is the founder of OSTraining. Originally from the UK, he now lives in Sarasota in the USA. Steve's work straddles the line between teaching and web development.

Popular New Posts

Blog Categories

Blog License

All our blog posts are published under the Creative Commons Attribution-NonCommercial license:

  • You can re-use these tutorials.
  • You can modify these tutorials.
  • You must link back to our original tutorial.
  • You can't use these tutorials commercially.

Full license details.

Join today and get access to 1,000's of books and videos. Learn WordPress, Drupal, Magento, Joomla and more! Sign up today!

Sours: https://www.ostraining.com/blog/drupal/twig/
Drupal 8 Layout and Theming, Lesson 23: Intro to twig template files

Using Twig in Drupal 8

After the official release, more and more Drupal developers are interested in learning about the new features of Drupal 8. So here is a chance to learn more about the Twig template engine in the newest blog post from our developer, the author of the popular posts on confuguration in Drupal 8 and tips for Drupal 8 developers. Here we go!

As you probably know, Drupal 8 uses Twig instead of PHPTemplate. This means that now, instead of the usual *.tpl.php files, we use the *.html.twig files.

Twig vs PHPTemplate

So let's take a look at the main features of Twig and its differences from PHPTemplate.

Outputting a variable:

<?php print $variable; ?> {{ variable }}

The If Operator:

<?php if ($variable_1 == “1”): ?> <div> <?php print $variable_2; ?> </div> <?php endif; ?> {% if variable_1 %} <div> {{ variable_2 }} </div> {% endif %}
<?php if (!empty($variable)): $variable2 = ‘value’; endif; ?> {% if variable is not empty %} set variable2 = ‘value ’ {% endif %}
<?php if (isset($variable)): $variable2 = ‘value’; endif; ?> {% if variable is defined %} set variable2 = ‘value ’ {% endif %}
<?php if ($variable < 0): $variable2 = ‘value’; endif; ?> {% if variable < 0 %} set variable2 = ‘value’ {% endif %}

Assigning a value to a variable:

<?php $variable = ’some_value’; ?> {% set variable = ‘some_value ’%}

Creating an array:

<?php $my_array = array(1,2,3,4,); ?> {% set my_array = [1,2,3,4,]%}
<?php $my_array = array('!element1'=>$var1, '!element2'=>$var2); ?> {% set my_array = {'!element1': var1, '!element2': val2} %}


<?php foreach ($users as $user) { } ?> {% for user in users %} {% endfor %}

Filters in Twig templates

In Twig templates, you can use various filters that change the variable outputting format directly in the template.

The available filters:

abs - returns the absolute value.


{# number = -5 #} {{ number|abs }} {# outputs 5 #}



{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %} <table> {% for row in items|batch(3, 'No item') %} <tr> {% for column in row %} <td>{{ column }}</td> {% endfor %} </tr> {% endfor %} </table>


<table> <tr> <td>a</td> <td>b</td> <td>c</td> </tr> <tr> <td>d</td> <td>e</td> <td>f</td> </tr> <tr> <td>g</td> <td>No item</td> <td>No item</td> </tr> </table>

capitalize — transforms the first character to uppercase and all the others to the lowercase


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


Twig in drupal 8

date — formats the date according to the specified format.


{{ '1447337804'|date("m/d/Y") }}



json_encode — returns JSON data presentation.

The json_encode PHP function is used.

first — returns the first element of the array or the line.


{{ [1, 2, 3, 4]|first }} {# outputs 1 #} {{ { a: 1, b: 2, c: 3, d: 4 }|first }} {# outputs 1 #} {{ '1234'|first }} {# outputs 1 #}

length — returns the first element of the array or the line.

lower — transforms the value to lowercase.

number_format — is filter to format numbers.


{{ 9800.333|number_format(2, '.', ',') }}



In order to process the variable through the t() function, you must use the t filter.

It looks like this.

<a href="{{ url('<front>') }}" title="{{ 'Home'|t }}" rel="home" class="site-logo"></a>

Debugging the Twig templates

To enable the option of debugging the Twig templates, go to the services.yml file and assign the true value to the debug parameter in the twig.config settings block. For easier development, you can also assign the false value to the cache parameter. This means, you will not have to clean the cache after making changes in the templates.

twig.config: debug: true cache: false

Setting your own template for an element

To set up your own template for an element, do the following:

function my_theme_theme($existing, $type, $theme, $path) { return array( 'block__system_menu_block' => array( 'template' => 'custom-menu-template', ), ); }


block__system_menu_block is the element for which you want to use the template;

custom-menu-template is the name of the template (the template filename will look like this: custom-menu-template.html.twig).

Hope this information will help you understand Drupal 8 better and make your development process easier and more enjoyable!:)

Sours: https://internetdevels.com/blog/using-twig-in-drupal-8

Twig in drupal 8 why

Twig PHP Templating Language

Drupal 8 is packed with many changes and new enhancements geared towards optimization, performance, and standardization. Finally, after years of working within a hybrid environment, we are now truly moving towards a system that separates logic, behavior, and design. In this blog, I will go 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 down to plain optimized PHP versus regular unoptimized PHP, thus enhancing speed and performance.

Why Twig?

The great advantages of using Twig is that it is fast, modern, and secure. It has been developed for use with Symfony, which is the new PHP framework behind 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 also easy to learn. It provides clear error messaging and is also very well documented.

Twig also provides consistent theming practices that can be taken up by other developers and site themers as projects get handed off from one development company (dev team) to another, as many often do. The way Twig is structured it decreases the possibilities for wide differences in coding and theming practices, techniques, non-standard coding, and hacks often seen when working with prior versions of Drupal, where sites have been developed and maintained by other people and teams. Standardized consistency is a key advantage to Twig’s efficiency.

Twig Syntax

There 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 understanding or “bird’s eye view” so-to-speak.

Open and Closing Tags

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

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

Template File Naming Conventions

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


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


Function Naming Conventions

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


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


Printing Variables

In prior versions of Drupal we would output a variable in the following manner:

In Drupal 8 using Twig, we will instead output the variable like this:

Assigning Variables

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

With Twig templates we instead do this:

Printing Hash Key Items

In the PHP templates we printed hash key items as follows:

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

Assigning an Array

Prior to Drupal 8, we would assign an array within the PHP template such as this:

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


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

With Twig templates we setup the conditional like this instead:

Control Structures

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

In the Twig template we do the following to setup a control structure:

Translate (‘t’ function)

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

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

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 be documented within a Twig template, there will be a need to expose additional variables within the scope of a Twig template such as those provided by modules.


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 you’ll need to set the debug parameter to “true” within the “twig.config” section of the Drupal 8 YML file. This file is located within “yoursite.com/sites/default/services.yml”. Find the “twig.config” parameters and set “debug” to “true”.



Note: This is extremely useful for development purposes, but be sure to change the “debug” parameter back to “false” when migrating and using this YML file on a production site.

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

Another advantage of Twig debugging is that the templates are automatically recompiled whenever a change in code is detected. This is achieved by by setting the “auto_reload” parameter to “true” within the YML file located at “yoursite.com/sites/default/services.yml”. As with the twig debug parameter, this too should be set back to “false” when migrating or using on a production site.

Outputting Variables – Using the “dump()” Function

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

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 can use the dump() function including the variable name as a parameter within your Twig template like this:

This is like 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. We now have 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 need for third party plugins and APIs. More importantly, HTML5 provides universal page elements common for theming such as: <article>, <header>, <footer>, <nav>, <section>, etc., which also enhances the semantic relevance of the page’s content.

CSS in Drupal 8

CSS in Drupal 8 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 Example:
Drupal 8 CSS Class Example:

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 way of structuring CSS to add flexibility and better maintainability as a project grows and is shared among multiple themers and/or handed off from one development team to another.

Theme Structure in Drupal 8

Basically, the structure of the theme’s page is the same as within Drupal 7. Here you have the “html”, “page”, “region”, “block”, “node”, and “field” layers, which make up the whole structure of a page and template files for each carry 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

See a visual representation of the theme’s structure layers here:

Drupal 8’s Theme .info File

The .info for the theming layer within Drupal 8 is somewhat similar to Drupal 7, however 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 key difference is how the stylesheets and regions parameters are declared. Also, stylesheets are now called and named per the SMACSS convention as referenced above. Below is a comparison of a theme’s .info file in Drupal 7 versus Drupal 8.

Drupal 7 theme.info Example:

Drupal 8 theme.info.yml Example:

Excluding Unwanted Stylesheets via “remove:”

In the Drupal 8 .info.yml example shown above, notice the “remove:” that is now available to use. This is quite handy because as you know Drupal has a nasty habit of loading an excessive number of stylesheets when there is a heavy use of numerous contrib modules in a site. Before themers had to live with this and create many CSS overrides in their theme’s custom CSS file in order to work around and override the style rules coming from all of those unwanted and often unneeded stylesheets. Now in Drupal 8, we have the “remove:” option available to us to quickly and easily exclude any particular stylesheet(s) we do not want to load into our theme. Not only does this alleviate the themer’s workload, but also provides another means to enhance the site’s loading performance. Loading fewer stylesheets will increase the speed in which the site and the site’s pages display for the end user.

Do You Still Need to Use a PHP-based Template Engine with Drupal 8?

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

Switching Drupal 8 Theme from Twig to PHP Example:

engine: phptemplate

Want help with your project? Contact us

Outputting Regions to a Page in Drupal 8

In Drupal 8, the ability to display regions within a page template has gotten easier in terms of coding. The basic principle is essentially the same, however 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 Example:

Drupal 8 Method for Displaying a Region Example:


Of course there are many more specifics and differences that can be covered between Drupal 8 and theming with Twig versus older versions of Drupal. However, this blog should serve well in highlighting the broad scope 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 way of rendering a site’s theme through the use of Twig. Drupal 8 has come far in separating design from functionality and so sites will be more optimized and better tuned for performance, in addition to lifting some of the redundant and formerly heavy workload previously required of themers. Of course there is a learning curve as with any change in technology, but once the basic concepts are understood all else should fall into place rather quickly.


Sours: https://kanopi.com/blog/twig-templating-engine-drupal-8/
Drupal 8 Theming - Part 02 - Disable Cache, Enable Twig Debug


Twig is a PHP templating engine and the default templating engine for Drupal 8. Part of the Symfony Framework, Twig syntax compiles templates down to plain PHP when rendered in the browser.

Twig offers advanced features like template inheritance, automatic escaping, variable filters and macros to improve development workflow. Drupal 8's Twig templates are "html.twig" templates, which means that you can mix Twig into HTML easier than you could mix PHP and HTML in Drupal 7’s PHP templates.

Syntax in Twig is somewhat different than PHP, with three main kinds of delimiters:

  • {{ }} prints the content of variables or expressions. This is the equivalent of PHP’s print or echo.
  • {% %} executes "if" statements, variable definitions or for loops.
  • {# #} adds template comments that are not rendered in the page.

A very basic Twig structure to print a message using a variable might look like:
{%  set message = ‘Welcome to  my great website‘ %}
{{ message }}



When starting to work in Twig, one of the first things you’re going to want to do is enable Twig debug and two key development modules.

As with Drupal 7 debugging, you’ll want to enable the Devel module right away. This will give you access to dpm and dsm functions to dig through available variables during debugging and site building. In Drupal 8 however, there is an additional module included in the Devel install called Kint.

Finding variables with Kint

Kint is very useful in Twig templates. You get all the available variables through dpm and dsm, plus all available methods—which is super handy for pulling in pieces from referenced entities. Methods reach can into other entities to pull fields, labels, and other useful information. Methods can also rewrite the variable output to format it in different ways or access array pieces. After you turn on Twig debugging, you can find variables by using {{ kint() }} inside your template.

Devel also has a nice cache clear function that will clear both the site cache and the image cache. Drupal 8 can be difficult when it comes to displaying image styles on a local environment—especially with responsive images. Devel cache clear will get your images displaying properly.

Twig debugging to get template suggestions

Enabling debugging is very easy in Drupal 8. Every D8 site comes with a default.services.yml file in the sites/default folder. Copy this file and rename it to services.yml ( and make sure you either .gitignore it or assume-unchanged, since you don’t want your debugging settings to be pushed to anywhere except your local machine).

In that services.yml file (around line 39) is a parameter called twig.config.  Change the debug variable to true, auto_reload to true, and the cache variable to false.  Save and clear cache.  You should now be able to use your browser’s inspector to tool to see all the possible template suggestions in the code as well as which templates are being used. This is equivalent to the drush vset theme_debug 1 command in D7. 

Custom Twig Templates

As with Drupal 7, any module or core template changes you make should be defined in a custom template. This is most easily done in Drupal 8 by copying the Twig template you want to change and either naming it more specifically or adding it to a custom folder at the bottom of your theme structure.

When deciding which Twig template to use, Drupal looks at both name specificity and directory hierarchy. For example, if you have a template called field.html.twig in your theme/templates directory, Drupal will use that in place of the core field.html.twig template because /theme/templates is lower in the hierarchy than /core. If you have a copy of that template in a theme/templates/zzz-custom directory in your theme and customize it there, Drupal will choose to use the one in /zzz-custom instead of because it is at the very bottom of the hierarchy—even though both it and the original are in your /theme/templates directory. This is often a handy trick for customizing templates that are defined by default themes like Classy since its not the best idea to rewrite default theme templates in case you need to reference or revert to them later.

To take it one step further, you can have a field.html.twig and field--field-long-text.html.twig. In that case, it makes no difference what directory they are in (as long as they are somewhere in the theme/templates directory). Drupal will use the field.html.twig for every field except fields with the machine name of field_long_text when it will use the template you created with the more specific name.

Twig naming conventions:

There are many different naming combinations for Drupal Twig templates, depending on the entity you are theming and how specific you are in naming the template. Entity hierarchy levels are always separated by two hyphens and words within each level by one hyphen.  

For example:

  • field.html.twig  (global top level for all field entities)
  • field--field-long-text.html.twig (second level for all fields with the machine name of long_text_)
  • field--field-long-text--page.html.twig (third level for fields with the machine name long text only on the Page content type).

You can use Twig debug to find template names and theme_suggestion hooks to create new template naming structures.


After setting up aD8 site and going into the theme folders for Bartik and Classy you'll notice that there are lot of templates in D8. This is because Drupal 8 really takes advantage of Twig’s template inheritance capabilities. Twig allows templates to be extended, included and embedded into other templates which allows for a very atomic approach to site building. Extends, Include, and Embed are quite similar, but there are some key points to be aware of.

Use Extends to inherit a parent twig template

Extends brings in the parent template (the one being extended) into the child template. No content outside of blocks defined in the parent template will be allowed in the child template. In a parent paragraphs template (paragraph.html.twig) there are some default classes and html structure you'll want to set that will be used in every paragraph bundle you create:

In a child text paragraph bundle (paragraph--text.html.twig) you would extend the parent template (paragraph.html.twig) and switch out the block content so the child gets the classes you want from the parent but uses its own content.

Since the parent template is being inherited with extends, all content in the child template must be inside a block defined in the parent. Content outside of parent blocks (as shown below) will not be allowed and will throw a Twig error on your site.

Use include to insert one template into another

Include also inherits content of a file, but also allows variables from the current template to replace those from the parent template. Include also differs from extends in that template you are including is included directly where the call is placed in the child. Think of it this way—extends is like bringing a parent template into a child template and changing some of the content of the parent in the child. Include brings a child template into a parent by inserting the entire child template into the parent a specific point. You could also insert an entire parent into a child and replace variables but not content.

The biggest advantage of this in my opinion is including templates from outside a Drupal site into a Drupal site or from one entity type to another. We use Pattern Lab as part of our approach to theming but while our Pattern Lab instance lives inside our Drupal theme it is technically outside of the Drupal site structure so it cannot use variables like {{ content.field_long_text }}. It even has a different suffix for files: paragraph.twig instead of paragraph.html.twig.

To get around that we use include instead of extends and use the ‘with’ function to replace variables from Pattern Lab in Drupal. The parent template paragraph--text.twig in Pattern Lab extends the Pattern Lab paragraphs.twig template to get the html structure then adds example {{ text }} variable content defined in a yml file. To get the final Pattern Lab example output.

Then in Drupal, the paragraph--text.html.twig file uses include to bring in the entire content of the Pattern Lab paragraph-text.twig file and replaces the {{ text }} variable with the Drupal output of the long text field in my text paragraph bundle {{ content.field_long_text }}.

The Drupal template uses the Component Libraries module to find the Pattern Lab Twig template and includes all the Pattern Lab structure but uses the Drupal text field for content.

Embed a twig template to replace variables and override parent blocks

Embed combines include and extends. You can embed a template in another template and replace the variables using 'with' and switch out block content from the child template you are embedding into the parent (or vice versa).

An example of this would be creating paragraphs demo content in Pattern Lab and bringing it into Drupal. Since Pattern lLb doesn’t have modules, we have to hand build the paragraph's HTML structure then exclude it in Drupal (since we don’t want the hand-built paragraphs html structure and Drupal’s).

In Pattern Lab the text.twig template gives basically the same HTML structure that the final Drupal paragraph bundle does but uses some dummy text from a yml file.

The Drupal template paragraph--text.html.twig both extends and embeds templates. It extends the Drupal paragraph.html.twig to add bring global classes and html structure into the text bundle template and it embeds the Pattern Lab text.twig template in place of the parent paragraph.html.twig content block while replacing the {{ text }} variable with the Drupal {{ content.field_long_text }} variable. Adding comments to the plwidgetopen and plwidgetclose blocks prevents them from printing the paragraph structure created in Pattern Lab.

With the setup above, you can theme the Drupal text bundle directly in Pattern Lab and have whatever structure is built around the text variable be reflected both there and around the Drupal long text field as well.

Pro Tips:

  1. It is often common to get ‘template not defined’ errors when using include, extends, or embed. You need to make sure that either the template you are inheriting is defined in the theme registry through a theme suggestion hook or that you define the correct path in your inheritance delimiter so drupal knows where to look {% include directory ~ '/templates/widgets/text/text.twig' %}.

  2. Blocks are your friend. Block structure can be switched out or added to at will with any of the inheritance methods and placeholder blocks can be used in parent templates to allow for later customization. You can use placeholder header and footer blocks in page.html.twig file to allow for custom scripts, libraries and other code to be added to different content types as needed.

Twig Variables

Variables are the name of the game in Twig templates. Otherwise, we would just be hard coding the website. Variables can be found using the Kint or Devel modules with the {{ kint() }} or {{ dump() }} commands. Often these commands are extremely memory heavy and can either crash your site or drive you made waiting for it to load—especially when find variables in views or array loops with a lot of items.

Reduce Kint memory timeouts with |keys filter

Since Kint is so memory heavy, you find yourself needing to increase the memory limit for the site. A couple of handy commands, {{ dump(_context|keys) }} and {{ kint(_context|keys) }}, can help to limit the dump content to just variables—excluding all their child arrays and available methods—which will make Kint very fast and solve the memory issue. You can drill down further by choosing a variable and using the |keys filter on that specific variable {{ kint(content|keys) }} to view its child variables.

Often you won’t be able to find the exact variable you need—like when you are trying to get a term name or id from an entity reference on a paragraph or node. In that case you can use Kint to drill into the entity level and use an available method to access those variables.  You can't use the |keys filter to get to methods, but you can skip to the deepest variable and go from there. This is also handy for nested paragraphs and media entities.

Set variables in your twig template

Once you have found the variable, you can either print it directly as listed in Kint or set it as a custom variable. You can also assign multiple values to a variable by using brackets [ ] (very useful for classes). Use ~  join plain text (encased in ‘ ’), to Twig syntax to create complex classes like paragraph--type--text.

For example, on a paragraph bundle for creating social media icons that has a taxonomy reference field for account platform, you'll want to be able to pass the platform name to the svg defined in paragraph--social-media.html.twig so that the right icon will be assigned when an editor chooses a platform.

First, define the social media platform name {% set name = content.field_account_platform.0[‘#taxonomy_term’].getName()|clean_class %}. This reaches through the paragraph (content) to look at the account platform field (.field_account_platform) to the first index (.0) then to the taxonomy term ([‘#taxonomy_term’] and uses a method (.getName() -- found in the Kint available method results) to find the term name. Then it uses Twig’s clean_class filter to turn the name to lowercase and replace spaces with hyphens so the output will be something the svg tag will like.

Now create the svg:

Pro Tips:

  1. Any Twig variable that does not have a hashtag can be print by using a . in front. For example, content[field_account_platform’] in Kint can be printed as {{ content.field_account_platform }}. Any variable that has a hashtag must be printed using the brackets and hashtag [‘#taxonomy_term’].

  2. Variables cannot be passed into incompatible entities without preprocessing or using include to replace them. Variables that are defined in Pattern Lab cannot be used in Drupal’s html.twig templates. Similarly node variables (like the node title) cannot be used in a block template without preprocessing the block to include node variables.

Twig Filters

Twig comes with some default filters you can use with your variables and expressions to further control the results. Twig filters are always preceded by a pipe. In the example above, we're using the clean_class filter to make sure that the paragraph bundle and view modes are always lowercase with hyphen spaces when assigning them to the classes variable.  

Some favorite filters are:

  • Join joins strings together with the separator you define.

  • Clean_class prepares string for use as a class name.

  • Clean_id works the same as clean_class but for id’s.

  • Date applies custom formatting to a timestamp. This is similar to the format_date filter except you don’t need to define the custom format in your Drupal admin configuration first.

  • Slice extracts a slice of a sequence or string.

  • Trim removes whitespace or defined characters from a string. You can define if you want to trim whitespace from the left or right side.  Note: Using hyphens inside your {{ }} delimiter will also trim whitespace. {{variable -}} would trim whitespace from the end of the variable string.

  • Without creates a copy of a variable array and prints it without the children variables you define. For instance, {{ content|without(‘field_long_text’) }} would print all of the content in the array without the long text field.

  • Keys returns keys of an array for when you want to iterate in a for loop.

  • Striptags removes all tags from the rendered output. You may also choose to allow certain tags.

You can add contributed Drupal modules to expand the available default filters or even write your own.

Twig Attributes

Twig also lets you assign and add to the attribute objects of variables and html structure. As in the classes variable above, this lets you add additional classes and other attributes to your template structure.

Twig Macros and Importing

In the last section, we learned that that variables cannot be passed into templates for incompatible entities without preprocessing or inclusion. The exception to this would be macros. A macro is basically a predefined, hard-coded thing defined in one template that you can import for use in any other template.

Define macros

Macros can be defined anywhere in your Twig template structure. One strategy is to define them in the template you are going to use them in or in the top-level template of that group. For instance a macro to build a specific block structure may be defined in block.html.twig and imported into templates within that block hierarchy. A better strategy might be to define all of the macros in one file that is not used anywhere on the site. That way you can add variable comments and whatever structure you want to create a master control area and then import the macros from that file to anywhere you need them.

Another great thing about macros is that they can accept arguments and function very similar to Sass mixins.

Import and use your macros

After you define the macro and the allowed arguments, you can then use it in any Twig template by importing it and printing using the {{ ]} delimiter. When importing and using macros, you need to import the template your macro is defined in (which can be _self if it's in the same template). Then you call that imported file and the macro name with your arguments in parenthesis.

Macros are helpful for anything you're going to be repeating a lot in templates, or for changing theming variables on the fly from a single point. You can define text in the macro and skip the arguments to instantly add and change theming classes.

The power of Twig macros with Pattern Lab

A macros.twig file set in Pattern Lab for for a base build could contain a whole list of variables that can be used to instantly change classes on pieces of a site to kick in pre-defined theming —basically your own little NASA control. You can define things in Pattern Lab like svg icon viewport positions based on an svg sprite or a fixed or non-fixed footer—or whatever else you can think of.

Then in the Pattern Lab page.twig, you import the macros file {% import "@base/global/05-macros/macros.twig" as styles %} and use its macro variables as classes. 

That Pattern Lab page.html is then extended into Drupal’s page.html.twig so that changing or removing the 'fixed' text in the macros.twig file will go from a fixed to static footer in both Pattern Lab and Drupal instantly. You could just add or remove the class manually right in the Pattern Lab page.twig and achieve the same result, but defining all the macros in one file makes them a lot easier and quick to change. This approach also lets you list them and their predefined and themed classes in Pattern Lab so that anyone could take one look at the stylesheet and know all the possible functionality at a glance.

Only a piece of the pie

Twig templating in Drupal 8 is an extremely large topic and there was no way to cover it all in this post. Look for Twig for Drupal 8 Development: Twig Templating Part 2 to be coming soon. Part 2 will cover creating variables with preprocessing, custom templates with theme suggestions, Views and Twig, and the Twig Tweak Module.

Sours: https://www.electriccitizen.com/citizen-blog/twig-drupal-8-development-twig-templating-part-1-2

You will also be interested:

How To Use Twig In Drupal 8

– Write Logic between the {%…%}, like, Conditions, Loop, Set variables values etc.

– EX:-
1. Set variable:-

Now, print the variable:- {{ var_name }}

2. Conditions:-

3. Loop:-

* How to use Twig Functions in Drupal 8:-
1. file_url($uri)

– file_url funcion fetch the relative path of file from the root and generate the uri for file.
– Syntax :-

– Ex:-

– Write the function in img tag for displaying on the front. Like,

– Fetch multiple files using file_url and fop loop:-
– Syntax:-[code]{% for item in content.file_machine_name[‘#items’] %}
{{ file_url(item.entity.uri.value) }}
{% endfor %}[code]

– Ex:-
drupal 8 twig
dom master 1

2. link($text, $url, $attributes)
– link () function is used for the create link with attributes.



drupal 8 twig
drupal twig display link

Mainly, this function is used for the render menu in template.

3. path ($name, $parameters, $options)

4. url($name, $parameters, $options)

Sours: https://www.cmsminds.com/blog/how-to-use-twig-in-drupal-8/

1867 1868 1869 1870 1871