Skip to main content
Ramdoss

How to use Twig template engine in Drupal 8


Twig template engine in Drupal 8

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

<?php 
/** 
 * @file
 * File description
 */
?>

Twig

{# 
/** 
 * @file
 * File description
 */
#}  

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

Variables

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 ([]):

{{ user.name }}
{{ user['name'] }}

Printing a variable

PHP Template

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

Twig

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

Printing a hash key item

PHP Template

<?php print $user['#item']['alt']; ?>

Twig

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

Assigning a variable

PHP Template

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

Twig

{% set new_var = content.comments %}

Assigning an array

PHP Template

<?php $arguments = array('!author' => $author, '!date' => $created); ?>

Twig

{% set arguments = {'!author': author, '!date': created} %}

Setting Variables

You can assign values to variables inside code blocks.

{% set user = 'ram' %}
{% set num = [1, 2] %}
{% set ral = {'foo': 'bar'} %}

Conditionals

PHPTemplate

<?php if ($content->comments): endif; ?>

Twig

{% if content.comments %} {% endif %}

PHPTemplate

<?php if (!empty($content->comments)): endif; ?>

Twig

{% if content.comments is not empty %} {% endif %}

PHPTemplate

<?php if (isset($content->comments)): endif; ?>

Twig

{% if content.comments is defined %} {% endif %}

PHPTemplate

<?php if ($count > 0): endif; ?>

Twig

{% if count > 0 %} {% endif %}

Filters

Check_plain:


PHP Template

<?php print check_plain($name); ?>

Twig

{{ name|striptags }}

Translate
 

PHP Template

<?php print t('Navigate'); ?>

Twig

{{ 'Navigate'|t }}

Implode a list

PHP Template

<?php echo implode(', ', $regions); ?>

Original Twig:

{{ regions | join(', ') }}

Drupal 8 Twig:

{{ regions }}

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.

Parameters:

  twig.config:
    debug: true

Dump

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:

{{ dump(user) }}


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

{{ dump(user) }}

Empty

Determine whether a variable is empty:

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

{% if user is empty %}
    ...
{% endif %}

Advantage of using Twig

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

<?php echo $variable ?>
<?php echo htmlspecialchars($variable, ENT_QUOTES, 'UTF-8') ?>
{{ variable }}
{{ variable|escape }}
{{ variable|e }}         {# shortcut to escape a variable #}

Template oriented syntax

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

{% for region in regions %}
    * {{ region.name }}
{% else %}
    No regions have been found.
{% endfor %}

Full featured

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

{% extends "sample.html" %}
{% block content %}
    Content of the page...
{% endblock %}

Functions

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:
 

{% for i in range(0, 3) %}
    {{ i }},
{% endfor %}

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:

Example

<h1>List</h1>
<ul>
    {% for region in regions %}
        <li>{{ region.name|e }}</li>
    {% endfor %}
</ul>

Example

The if tag can be used to test an expression:

{% if regions|length > 0 %}
    <ul>
        {% for region in regions %}
            <li>{{ region.name|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Comments

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:

{# note: disabled template because we no longer use this
    {% for region in regions %}
        ...
    {% endfor %}
#}

 

Comments

Leave Your Comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
 

start with anubavam today

You have an idea we have engineers to convert your ideas into reality

Request Quote