Drupal twig tutorial

Twig is more powerful than php templates. And also provides more security compared to PHP template engine.

From Drupal 8 onwards, Drupal uses twig templates in presentation layer.

Here we are going to discuss some of the most commonly used syntax and code snippets in twig templates while developing Drupal based websites.

In php template, we used to name template file as Your-File-Name.tpl.php

In twig template name file will be as Your-File-Name.html.twig

In this article we are discussing below points.

  • Twig print variable {{ }}
  • Twig comments {# #}
  • Twig expression {% %}
  • If condition Check for null in twig
  • For loop -Array  listing in twig
  • Filters
  • Functions in twig
  • Twig Attributes
  • Including and Extending templates
  • Importing css and js using asseturl
  • Links to other pages in twig templates
  • Translation of strings in twig template
  • Concatenating string in twig

Twig print variable {{ }}

Printing variables in twig template file. Also prints result of an expression in to the template. Here we are doing few examples for printing values in templates using {{ }}

We are adding below base_path parameter in variable array in .theme file preprocess function.

function YOUR_THEME_preprocess(&$variables) {
   $host = \Drupal::request()->getHost();
  $variables['base_path'] = $host;
}

So base_path variable has value as hostname. Here my host name is digitalnadeemlocaltest.com

Instead of base_path you can provide any name. you can print this variable in twig template as below.

{{ base_path }}

I placed this in page-front.html.twig

So it is display as below.

Twig comments {#  #}

This is same as PHP comments  block /* —your comment —*/

You can see comments existing twig  templates.

{#

/**

* our comments

*/

#}

Twig expression {%  %}

Expressions will be anything like if loop, For loop, setting variable using set key word. So here in my twig file I have below if condition. This is checks for variable is exist or not.

{% if base_path  %}
  <div>{{ base_path }}</div>
{% endif %}

You can set a variable in twig and print as below.

{% set my_var = 'Hi I am Nadeem' %}
		{% if my_var  %}
		  <div>{{ my_var }}</div>
		{% endif %}

Check for null in twig using if condition

Is null checks whether the value is null.

http://twig.sensiolabs.org/doc/tests/null.html

{% if var is null %}

{# do something #}

{% endif %}

 

is defined checks whether the variable is defined:

{% if var is not defined %}

{# do something #}

{% endif %}

is sameas test, which does a type strict comparison of two values, might be of interest for checking values other than null (like false):

{% if var is sameas(false) %}

{# do something %}

{% endif %}

For loop  -Array  listing in twig

In our .theme file we can create an array . here in page preprocess function create an array of items and assign to variable $variables with key items.

See the code snippet below.

function YOUR_THEME_preprocess_page(&$variables) {
	 $item_list = array(
	     array('item'=>'item1','quantity'=>'12'),
		 array('item'=>'item2','quantity'=>'10')
	 );
	 
	 $variables['items'] = $item_list;
 }

Display this items in twig template in a table form as below.

<table>
		<th>Name </th>
		<th>Quantity</th>
       {% for item in items %}
	   <tr>
	   <td> {{ item['item']}} </td>
	   <td> {{ item['quantity']}}</td>
	   </tr>
	   {% endfor %}
	   </table>

display of table will be as below.

Filters

Filters are used  to modify variables in twig. For example making string to all uppercase. Twig comes with different kinds of filters.

Complete list you can see here. https://twig.symfony.com/doc/3.x/filters/index.html

Here we are discussing about Drupal specific filters and some of other important filters.

See some of below examples.

{{ 'now' | date }}   // prints April 10, 2021 11:22 
{{ "now"|date("m/d/Y") }    //prints 04/10/2021

{{ 'home' | upper }} {# /** prints UPPER   **/    #}    for single line

For whole block

{% filter upper %}

This sample text

sample text

{% endfilter %}

Translation filter -trans

This will run t()  function in Drupal and translates the string.

See the below usage

{% trans %}

Node was created on  {{ date }}.

{% endtrans %}

Also you can use t in filter

{{ ‘Home’ | t }}

Submitted by {{ ‘nadeem’|placeholder }}

<em class=”placeholder”>nadeem</em>

Functions in twig

You can see about details  about twig functions that can be used in Drupal twig templates

https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates

Twig Attributes

Attribute is an object which stores attribute values.

By default, the following attribute object variables are available to all templates: attributes, title_attributes, and content_attributes.

All attributes of a template  can be printed in a div as provided below in your node template.

<div{{ attributes }}>test div</div>

Clear cache and see the div. you can see below classes and other attributes added to the div tag.

You can add a single class to attributes as below

<div{{ attributes.addClass(‘my-new-class’) }}></div>

 

You can add multiple classes using below code snippet.

{%  set classes = [    ‘header’,    ‘footer’,  ]%}<div{{ attributes.addClass(classes) }}></div>

 

You can check whether a css class exist or not using below code snippet.

{% if attributes.hasClass(‘myClass’) %}

{# logic comes here #}

{% endif %}

You can see more details about some of the most commonly used methods in below link.

https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

Including and Extending templates

Here we are going to explain different ways of extending and inheriting templates and its variables.

Extending attributes

Copy below files in to your themes templates path.

YOUR_PROJECT\core\themes\classy\templates\field\field–text.html.twig

YOUR_PROJECT\core\themes\classy\templates\field\field–text-with-summary.html.twig

You can see below line in field–text-with-summary.html.twig.

{% extends “field–text.html.twig” %}

So in field–text.html.twig file there are multiple attributes available. So in field–text-with-summary.html.twig  , but extending above file, same attributes available in summery file. Now in summey file  we are adding our custom class as below.

Below line adding additional classes.

{% set attributes = attributes.addClass(‘our_custom_class’) %}

Now clear the cache and open a node page. You can see our class in div.

Extend templates Using blocks

Using blocks declaration in parent template we can alter whatever comes in block in child template.

So here in our field–text.html.twig we have below block

{% block YOUR_BLOCK_NAME %}

//  content here which may be alerted in other templates

{% endblock %}

So in field–text-with-summary.html.twig we are altering above block as below by proving same block name what you provided in parent template.

{% extends “field–text.html.twig” %}

{% block YOUR_BLOCK_NAME %}

//  alter here

{% endblock %}

I have placed below code snippet in file-text.html.twig

{% block custom_content %}

parent content

{% endblock %}

And below content in field–text-with-summary.html.twig

{% extends “field–text.html.twig” %}

{% block custom_content %}

parent content altered

{% endblock %}

Clear the cache.

This will print parent content altered in your article page.

If we remove block from   field–text-with-summary.html.twig. article page will show   parent content  this rendered from file-text.html.twig

Include external template

Use below code snippet in order to include templates in twig templates.

{% include ‘folder_name/header.html.twig’ %}

https://symfony.com/doc/current/templates.html#template-inheritance-and-layouts

Importing css and js using asseturl

for importing assets like images and css files, you can use below code snippet for getting the absolute path.

<img src=”{{ base_path ~ directory }}/images/logo.jpg” alt=”My Logo” />

Also add below code in your theme preprocess function.

$variables[‘base_path’] = base_path();

Links to other pages in twig templates

url()  function provides absolute path for given path name and parameters

path()  function provides relative path for given path name and parameters

 

{ url(‘<front>’) }}

Outputs http://digitalnadeemlocaltest.com/

{{ path(‘<front>’) }}

Outputs  /

 

Below snippets used for getting path of nodes.

{{ url(‘entity.node.canonical’,{‘node’:node.id}) }}

{{ path(‘entity.node.canonical’,{‘node’:node.id}) }}

For more about most commonly used function refer below link.

https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates

Translation of strings in twig template

As discussed, earlier trans filter is used for translation of strings. If your website configured for multilingual you can use below snippets to translate

You can use any of the below syntax for single line translation

{{  ‘sample string’  |t}}

{{  ‘sample string’ |trans}}

You can use below trans filter block for multiline translation.

{% trans %}

Sample string multiline

Sample string multiline.

{% endtrans %}

Concatenating string in twig

You can use ~ operator for concatenating stings in twig.

{{ ‘http://’ ~ ‘digitalnadeem.com’ }}

{{ (‘http://’ ~ digitalnadeem.com) | trans }}

This will output as   http://digitalnadeem.com

Get Free E-book
Get a free Ebook on Drupal 8 -theme tutorial
I agree to have my personal information transfered to MailChimp ( more information )
if you like this article Buy me a Coffee this will be an ispiration for me to write articles like this.

You may also like...