Introduction
Twig is a modern template engine for PHP.
It lets you separate business logic from presentation logic, by using template files that don't contain any PHP, and are unaware of any of Drupal's internal workings.
Twig's concern is compiling Twig templates into HTML; it provides a small number of programming language concepts such as:
- Variables
- Loops (iterations)
- If/then/else statements (selections)
- Arrays and Objects that represent data
- Predefined functions and filters
We will discuss each of these concepts in this course.
How does Twig work?
Systems, like Drupal, that use Twig for their templates generally go through the following steps:
- System gathers data it wants to display.
- System tells Twig Engine to compile one or more Twig template files into HTML, and passes along the required data.
- Twig compiles the template(s), substituting the template's variables with the data it receives.
- Twig sends the compiled chunk(s) of HTML back to the System.
- System merges the compiled HTML chunks into a complete HTML document and sends that back to the browser for display.
Example 1
Here's an example of a Twig file that uses three variables:
<h2>Short Bio</h2>
<p>First name: {{ first_name }}</p>
<p>Last name: {{ last_name }}</p>
<p>Occupation: {{ occupation_name }}</p>When Twig compiles this template into HTML, it replaces the variables with actual data.
Assuming Twig receives the values "Jane", "Doe", and "data scientist", the compiled HTML will be:
<h2>Short Bio</h2>
<p>First name: Jane</p>
<p>Last name: Doe</p>
<p>Occupation: data scientist</p>Example 2
The following demonstrates Twig's three types of delimiters, and gives a preview of how to use filters and iterations:
{# This is a line of comment #}
<p>My name is {{ dog.name }} and I'm a good boy!</p>
<p>My friends are {{ dog.friends | join(', ') }}.</p>
My favourite activities are:
<ul>
{% for activity in dog.fav_activities %}
<li>{% {{ activity }} %}</li>
{%%}
</ul>When compiled with some actual dog data, the resulting HTML would be:
<p>My name is Rufus and I'm a good boy!</p>
<p>My friends are Princess, Bobby, Max, Snuffles.</p>
My favourite activities are:
<ul>
<li>chasing sticks</li>
<li>playing with tennis balls</li>
<li>going for long walks on the beach</li>
</ul>Delimiter types
From the previous examples you can identify three types of delimiters used in Twig:
{# #}: used for comments{{ }}: used to print variables{% %}: used for basic programming logic such as iterations (loops) and selections (if/then/else).
These are the building blocks of the Twig syntax used in most Drupal templates.
Throughout the next units you will see more detailed examples of Twig syntax in action.
Summary
- Twig is a template engine.
- Twig templates are a mix of html and Twig syntax.
- Twig uses three types of delimiters:
{# #}for comments{{ }}to print output{% %}for logic