ZetCode

PHP Twig

last modified November 14, 2026

PHP Twig tutorial shows how to generate HTML and text documents with the Twig template engine. The examples were run with Twig 3.30 and PHP 8.5; the Symfony example uses Symfony 8.1.

Twig

Twig is a template engine for PHP. It is developed by the Symfony team and is the default template engine of the Symfony framework, but it is a standalone library that can be used in any PHP application. Twig templates are text files, usually with the .html.twig extension, that mix static content such as HTML with Twig constructs.

A template engine combines templates with a data model to produce documents. The template defines the static parts of a document and the places where dynamic data is inserted. Template engines are used to generate HTML pages, e-mails, configuration files or source code. They separate the presentation from the application logic: PHP code prepares the data and the template decides how it looks.

Twig has the following features:

Installation

We install Twig with Composer. Every example in this article starts with require __DIR__ . '/vendor/autoload.php';, which loads the classes installed by Composer. The template files are placed into the templates directory.

$ composer require twig/twig
$ mkdir templates

Twig first example

The simplest way to try Twig is the ArrayLoader, which takes the templates from a PHP array.

string_template.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\ArrayLoader;

$loader = new ArrayLoader([
    'greeting' => 'Hello {{ name }}! Today is {{ day }}.',
]);

$twig = new Environment($loader);

echo $twig->render('greeting', ['name' => 'Jan', 'day' => 'Saturday']);
echo "\n";

The Environment object is the central part of Twig. It stores the configuration and the extensions and it loads and renders templates.

$loader = new ArrayLoader([
    'greeting' => 'Hello {{ name }}! Today is {{ day }}.',
]);

The loader knows where the templates are. The ArrayLoader maps template names to template source code. It is useful in tests and for short templates stored in a database.

echo $twig->render('greeting', ['name' => 'Jan', 'day' => 'Saturday']);

The render method takes the name of a template and the data, which is an associative array. The keys of the array become template variables. The {{ name }} expression prints the value of the name variable.

$ php string_template.php
Hello Jan! Today is Saturday.

Loading templates from files

In real applications, templates are stored in files and loaded with the FilesystemLoader.

first.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

echo $twig->render('first.html.twig', [
    'name' => 'John Doe',
    'occupation' => 'gardener',
]);

The FilesystemLoader loads templates from the given directory. It can also take an array of directories, which are searched in order.

templates/first.html.twig
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First example</title>
</head>
<body>

<p>
    {{ name }} is a {{ occupation }}
</p>

</body>
</html>

This is the template file. The name and occupation variables are replaced with the values passed to render.

$ php first.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First example</title>
</head>
<body>

<p>
    John Doe is a gardener
</p>

</body>
</html>

Twig syntax

Twig uses three kinds of delimiters:

Inside the delimiters we use expressions built from variables, literals, operators, filters, functions and tests. Filters are applied with the | character and tests with the is operator.

syntax.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$words = ['sky', 'falcon', 'forest'];

echo $twig->render('syntax.html.twig', ['words' => $words]);

The script passes an array of words to the template.

templates/syntax.html.twig
{# this comment is not part of the output #}
<p>The list has {{ words|length }} words</p>

<ul>
{% for word in words %}
    <li>{{ word }}</li>
{% endfor %}
</ul>

The length filter returns the number of elements and the for tag loops over the array. Twig removes the first newline after a tag, so the lines with {% for %} and {% endfor %} leave no empty lines in the output. The comment does not appear in the output.

If a template must output the delimiters literally, for example because it contains templates of a JavaScript framework, we wrap that part in {% verbatim %} and {% endverbatim %}; Twig does not parse it.

$ php syntax.php
<p>The list has 3 words</p>

<ul>
    <li>sky</li>
    <li>falcon</li>
    <li>forest</li>
</ul>

Whitespace control

Twig keeps the whitespace of the template. With the - modifier we remove all whitespace, including newlines, on the side of a tag where the modifier is placed. The ~ modifier removes spaces and tabs, but keeps newlines.

whitespace.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$words = ['sky', 'falcon', 'forest'];

echo $twig->render('whitespace.html.twig', ['words' => $words]);

The script passes the same three words to the template.

templates/whitespace.html.twig
<ul>
{% for word in words %}
    <li>{{ word }}</li>
{% endfor %}
</ul>

<p>
{%- for word in words -%}
    {{ word }}{{ loop.last ? '' : ', ' }}
{%- endfor -%}
</p>

<p>
    {{~ words|first ~}}    
</p>

The first list keeps the default formatting. In the paragraph, the {%- ... -%} tags remove the whitespace around the words, so the whole list ends up on one line. The loop.last variable tells us whether we are in the last iteration, so we do not print the comma after the last word. In the last paragraph, the ~ modifier removes the indentation before the word and the trailing spaces after it, but the newlines stay.

$ php whitespace.php
<ul>
    <li>sky</li>
    <li>falcon</li>
    <li>forest</li>
</ul>

<p>sky, falcon, forest</p>

<p>
sky
</p>

Variables and attributes

The dot operator accesses attributes of arrays and objects. For user.name, Twig tries an array key, a public property, a method name(), and the getters getName(), isName() and hasName(), in this order. The template does not need to know whether the data is an array or an object.

attributes.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

class User
{
    public function __construct(
        public string $name,
        private string $email,
        private bool $active,
        public ?User $manager = null,
    ) {}

    public function getEmail(): string
    {
        return $this->email;
    }

    public function isActive(): bool
    {
        return $this->active;
    }

    public function initials(string $sep = ''): string
    {
        $parts = array_map(fn($p) => $p[0], explode(' ', $this->name));

        return implode($sep, $parts);
    }
}

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$boss = new User('Roger Roe', 'roger@example.com', true);
$user = new User('John Doe', 'john@example.com', false, $boss);
$city = ['name' => 'Bratislava', 'population' => 475_000];

echo $twig->render('attributes.html.twig', [
    'user' => $user,
    'boss' => $boss,
    'city' => $city,
]);

The User class has a public name property, private fields with getters, a method with an argument and an optional manager.

templates/attributes.html.twig
<p>{{ city.name }} has {{ city['population'] }} inhabitants</p>

<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<p>Active: {{ user.active ? 'yes' : 'no' }}</p>
<p>Initials: {{ user.initials }}, {{ user.initials('.') }}</p>
<p>Manager: {{ user.manager.name }}</p>
<p>Manager of manager: {{ boss.manager?.name ?? 'none' }}</p>

The city['population'] subscript syntax works too; it is needed when the key is in a variable or contains characters such as a hyphen. The private email field is read through getEmail and active through isActive. Methods are called with or without parentheses; arguments are passed in parentheses.

<p>Manager of manager: {{ boss.manager?.name ?? 'none' }}</p>

Roger Roe has no manager. The null-safe operator ?., available since Twig 3.23, returns null instead of continuing the chain, and the null-coalescing operator ?? provides a default value.

$ php attributes.php
<p>Bratislava has 475000 inhabitants</p>

<p>Name: John Doe</p>
<p>Email: john@example.com</p>
<p>Active: no</p>
<p>Initials: JD, J.D</p>
<p>Manager: Roger Roe</p>
<p>Manager of manager: none</p>

Operators

Twig supports arithmetic, comparison, logical and string operators. Some of them are written as words, for example and, or, not, in or starts with. Templates do not have to produce HTML; this example uses a plain text template with the .txt.twig extension.

operators.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

echo $twig->render('operators.txt.twig', [
    'a' => 7,
    'b' => 2,
    'name' => 'Lucy',
    'colours' => ['red', 'green', 'blue'],
    'nickname' => null,
]);

We pass numbers, a string, an array and a null value to the template.

templates/operators.txt.twig
{{ a }} + {{ b }} = {{ a + b }}
{{ a }} / {{ b }} = {{ a / b }}
{{ a }} // {{ b }} = {{ a // b }}
{{ a }} % {{ b }} = {{ a % b }}
{{ a }} ** {{ b }} = {{ a ** b }}

{{ 'Hello ' ~ name ~ '!' }}
{{ "Hello #{name}, #{a} times #{b} is #{a * b}" }}

{{ a > b ? 'a is greater' : 'b is greater' }}
{{ nickname ?? 'no nickname' }}
{{ 'green' in colours ? 'green found' : 'green missing' }}
{{ 'black' not in colours ? 'black missing' }}
{{ name starts with 'L' ? 'starts with L' }}
{{ name matches '/^[A-Z][a-z]+$/' ? 'capitalized word' }}
{{ (a > 5 and b < 5) ? 'both true' }}
{{ a === 7 ? 'identical' }}
{{ (1..5)|join(', ') }}
{{ ('a'..'e')|join }}

The / operator returns a float when the result is not a whole number, while // is the integer division. The ~ operator concatenates strings. Inside double-quoted strings, #{...} interpolates an expression.

The short ternary a ? b without the else part prints an empty string if the condition is false. The matches operator takes a regular expression and === compares both value and type. The .. operator creates a sequence of numbers or letters.

{{ (1..5)|join(', ') }}

Filters have a higher precedence than most operators. Without the parentheses, 1..5|join(', ') would apply the filter to 5 only; the result is a range array, which cannot be printed. The same applies to the unary minus: -5|abs means -(5|abs). When in doubt, we use parentheses.

$ php operators.php
7 + 2 = 9
7 / 2 = 3.5
7 // 2 = 3
7 % 2 = 1
7 ** 2 = 49

Hello Lucy!
Hello Lucy, 7 times 2 is 14

a is greater
no nickname
green found
black missing
starts with L
capitalized word
both true
identical
1, 2, 3, 4, 5
abcde

Filters

Filters modify values. A filter is applied with the | character; arguments are passed in parentheses and filters can be chained.

filters.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$words = ['sky', 'mountain', 'falcon', 'forest', 'rock', 'blue'];
$sentence = 'today is a windy day';

echo $twig->render('filters.txt.twig', [
    'words' => $words,
    'sentence' => $sentence,
    'drink' => 'šumivé víno',
    'price' => 1234567.891,
    'tags' => 'php, twig , symfony ',
    'nickname' => '',
]);

We pass an array of words, several strings and a number to the template.

templates/filters.txt.twig
{{ words|length }}
{{ words|join(', ') }}
{{ words|join(', ', ' and ') }}
{{ words|first }} {{ words|last }}
{{ words|sort|join(' ') }}
{{ words|reverse|join(' ') }}
{{ words|slice(1, 3)|join(' ') }}
{{ words[2:]|join(' ') }}

{{ sentence|upper }}
{{ sentence|title }}
{{ sentence|capitalize }}
{{ drink|capitalize }} {{ drink|length }}
{{ sentence|replace({'windy': 'sunny', 'today': 'tomorrow'}) }}
{{ tags|split(',')|map(t => t|trim)|join('|') }}

{{ price|number_format }}
{{ price|number_format(2, ',', ' ') }}
{{ price|round(1, 'floor') }}
{{ (-5)|abs }}
{{ nickname|default('anonymous') }}
{{ '%s has %d letters'|format(drink, drink|length) }}

The join filter takes an optional second argument used before the last element. The words[2:] notation is a shortcut for the slice filter. The string filters are Unicode-aware: capitalize correctly uppercases the accented letter š and length counts characters, not bytes.

The replace filter takes a mapping of search and replacement strings. The split filter returns an array, which we clean with the map filter. The number_format filter takes the number of decimals, the decimal point and the thousands separator. The default filter returns its argument if the value is undefined or empty. The format filter works like sprintf.

$ php filters.php
6
sky, mountain, falcon, forest, rock, blue
sky, mountain, falcon, forest, rock and blue
sky blue
blue falcon forest mountain rock sky
blue rock forest falcon mountain sky
mountain falcon forest
falcon forest rock blue

TODAY IS A WINDY DAY
Today Is A Windy Day
Today is a windy day
Šumivé víno 11
tomorrow is a sunny day
php|twig|symfony

1,234,568
1 234 567,89
1234567.8
5
anonymous
šumivé víno has 11 letters

Arrow functions

The filter, map, reduce, sort and find filters accept arrow functions, which work like short closures in PHP.

arrow_functions.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$products = [
    ['name' => 'Keyboard', 'price' => 45, 'stock' => 12],
    ['name' => 'Monitor', 'price' => 230, 'stock' => 0],
    ['name' => 'Mouse', 'price' => 19, 'stock' => 40],
    ['name' => 'Webcam', 'price' => 70, 'stock' => 3],
];

echo $twig->render('arrow_functions.txt.twig', ['products' => $products]);

We work with an array of products.

templates/arrow_functions.txt.twig
In stock: {{ products|filter(p => p.stock > 0)|column('name')|join(', ') }}
Names: {{ products|map(p => p.name|upper)|join(', ') }}
Total value: {{ products|reduce((sum, p) => sum + p.price * p.stock, 0) }}
Cheapest first: {{ products|sort((a, b) => a.price <=> b.price)|column('name')|join(', ') }}
First over 100: {{ (products|find(p => p.price > 100)).name }}

{% for p in products|filter(p => p.price < 100) %}
{{ p.name }}: {{ p.price }} EUR
{% endfor %}

The filter filter keeps the products in stock and column extracts their names. The reduce filter computes the total value of the stock; its second argument is the initial value. The sort filter takes a comparison function, which uses the spaceship operator. The find filter returns the first matching element.

$ php arrow_functions.php
In stock: Keyboard, Mouse, Webcam
Names: KEYBOARD, MONITOR, MOUSE, WEBCAM
Total value: 1510
Cheapest first: Mouse, Keyboard, Webcam, Monitor
First over 100: Monitor

Keyboard: 45 EUR
Mouse: 19 EUR
Webcam: 70 EUR

Conditions

The if tag with optional elseif and else branches executes parts of a template conditionally.

conditions.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

foreach ([45, 72, 98] as $score) {
    echo $twig->render('conditions.txt.twig', ['score' => $score]);
}

We render the same template three times with different scores.

templates/conditions.txt.twig
{% if score >= 90 %}
{{ score }}: excellent
{% elseif score >= 60 and score < 90 %}
{{ score }}: passed
{% else %}
{{ score }}: failed
{% endif %}

Conditions can be combined with the and, or and not operators.

$ php conditions.php
45: failed
72: passed
98: excellent

Loops

The for tag loops over arrays, iterable objects and sequences. Inside the loop, the special loop variable holds information about the current iteration.

loops.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$capitals = ['Slovakia' => 'Bratislava', 'Hungary' => 'Budapest',
    'Poland' => 'Warsaw', 'Austria' => 'Vienna'];

$users = [
    ['name' => 'John Doe', 'active' => false],
    ['name' => 'Lucy Smith', 'active' => false],
    ['name' => 'Peter Holcombe', 'active' => false],
];

echo $twig->render('loops.html.twig', [
    'capitals' => $capitals,
    'users' => $users,
]);

We pass an associative array of capitals and a list of users, none of whom is active.

templates/loops.html.twig
<table>
{% for country, capital in capitals %}
    <tr class="{{ cycle(['odd', 'even'], loop.index0) }}">
        <td>{{ loop.index }}/{{ loop.length }}</td>
        <td>{{ country }}</td>
        <td>{{ capital }}</td>
    </tr>
{% endfor %}
</table>

{% for country in capitals|keys %}
{{ loop.first ? 'Countries: ' }}{{ country }}{{ loop.last ? '.' : ', ' }}
{%- endfor %}


<ul>
{% for user in users|filter(u => u.active) %}
    <li>{{ user.name }}</li>
{% else %}
    <li>No active users found</li>
{% endfor %}
</ul>

{% for i in 10..0 %}{{ i }} {% endfor %}

With for country, capital in capitals we get both the keys and the values. The loop.index variable is the current iteration counted from 1, loop.index0 counted from 0, and loop.length is the number of items. The cycle function alternates the CSS classes. The keys filter gives us the keys only, and loop.first and loop.last mark the first and last iterations.

{% for user in users|filter(u => u.active) %}
    <li>{{ user.name }}</li>
{% else %}
    <li>No active users found</li>
{% endfor %}

The else part is rendered when the sequence is empty. We select the active users with the filter filter. Older tutorials use the {% for user in users if user.active %} form; this syntax was removed in Twig 3.0 and now ends with a syntax error.

$ php loops.php
<table>
    <tr class="odd">
        <td>1/4</td>
        <td>Slovakia</td>
        <td>Bratislava</td>
    </tr>
    <tr class="even">
        <td>2/4</td>
        <td>Hungary</td>
        <td>Budapest</td>
    </tr>
    <tr class="odd">
        <td>3/4</td>
        <td>Poland</td>
        <td>Warsaw</td>
    </tr>
    <tr class="even">
        <td>4/4</td>
        <td>Austria</td>
        <td>Vienna</td>
    </tr>
</table>

Countries: Slovakia, Hungary, Poland, Austria.

<ul>
    <li>No active users found</li>
</ul>

10 9 8 7 6 5 4 3 2 1 0 

Assigning variables

The set tag assigns values to variables inside a template. Since Twig 3.23, values can also be assigned with the = operator and arrays and objects can be destructured.

variables.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$words = ['sky', 'mountain', 'falcon', 'forest', 'rock', 'blue'];
$user = ['name' => 'Roger Roe', 'city' => 'Prague'];

echo $twig->render('variables.txt.twig', ['words' => $words, 'user' => $user]);

We pass a list of words and an array with user data.

templates/variables.txt.twig
{% set sorted = words|sort %}
{% set count, maxlen = words|length, max(words|map(w => w|length)) %}
Sorted: {{ sorted|join(' ') }}
{{ count }} words, the longest has {{ maxlen }} letters

{% set signature %}
--
{{ user.name }}, {{ user.city }}
{% endset %}
{{ signature|trim }}

{% do total = words|reduce((acc, w) => acc + w|length, 0) %}
Total letters: {{ total }}

{% do [first, second] = words %}
{% do {name, city} = user %}
{{ first }}, {{ second }}; {{ name }} lives in {{ city }}

{% with { greeting: 'Hi' } %}
Inside with: {{ greeting }} {{ name }}
{% endwith %}
Outside with: {{ greeting ?? 'greeting is not defined' }}

The first set stores the sorted words; the second one assigns two variables at once. The max function returns the greatest value from the array of word lengths. In its block form, {% set %}...{% endset %} captures the rendered content of the block into a variable.

The do tag evaluates an expression without printing it. We use it with the = operator and with destructuring, which takes the elements of a sequence by position and of a mapping by key. The with tag creates an inner scope: variables defined in it are not visible outside.

$ php variables.php
Sorted: blue falcon forest mountain rock sky
6 words, the longest has 8 letters

--
Roger Roe, Prague

Total letters: 31

sky, mountain; Roger Roe lives in Prague

Inside with: Hi Roger Roe
Outside with: greeting is not defined

Tests

Tests check a value and return a boolean. They are applied with the is operator and negated with is not.

tests.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$values = ['', null, 'rock', '   ', 'forest', 12, [], [1, 2]];

echo $twig->render('tests.txt.twig', ['values' => $values]);

We have an array of values of various types, including empty, null, and blank strings.

templates/tests.txt.twig
{% for value in values %}
{{ loop.index }}: {% if value is null -%}
    null
{%- elseif value is iterable -%}
    iterable, {{ value is empty ? 'empty' : value|length ~ ' items' }}
{%- elseif value is empty -%}
    empty string
{%- elseif value|trim is empty -%}
    blank string
{%- elseif value is same as(12) -%}
    the integer 12, {{ value is even ? 'even' : 'odd' }}, {{ value is divisible by(3) ? 'divisible by 3' }}
{%- else -%}
    {{ value }}
{%- endif %}

{% endfor %}
{{ undefined_var is defined ? 'defined' : 'undefined_var is not defined' }}

The null test (also called none) checks for null. The empty test is true for an empty string, an empty array, null and false. A string of spaces is not empty, so we apply the trim filter first. The iterable, same as, even, odd and divisible by tests do what their names say. The defined test checks whether a variable exists.

$ php tests.php
1: empty string
2: null
3: rock
4: blank string
5: forest
6: the integer 12, even, divisible by 3
7: iterable, empty
8: iterable, 2 items
undefined_var is not defined

Automatic escaping

Data from users must not be printed into HTML pages unescaped; otherwise an attacker could inject JavaScript code (a cross-site scripting attack, XSS). Twig escapes all printed values for HTML by default. The raw filter turns off escaping for a single value and the escape filter (or its alias e) applies a specific escaping strategy.

escaping.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$comment = '<script>alert("pwned")</script> & <b>bold</b>';
$query = 'twig & php';
$bio = '<em>Gardener</em> from Bratislava';

echo $twig->render('escaping.html.twig', [
    'comment' => $comment,
    'query' => $query,
    'bio' => $bio,
]);

The comment contains a script and HTML tags. The biography contains trusted HTML markup.

templates/escaping.html.twig
<p>{{ comment }}</p>
<p>{{ bio|raw }}</p>
<p>{{ bio|striptags }}</p>

<a href="/search?q={{ query|url_encode }}">Search</a>
<input value="{{ comment|e('html_attr') }}">
<script>
    let msg = '{{ query|e('js') }}';
</script>

{% autoescape false %}
<p>{{ bio }}</p>
{% endautoescape %}

The comment is printed as harmless text. We trust the biography, so we print it with raw; striptags removes the tags instead. Different contexts need different escaping: the url_encode filter is for URL parts, e('html_attr') for HTML attribute values and e('js') for JavaScript strings. The autoescape tag turns escaping on or off for a part of a template.

Escaping is configured with the autoescape option of the environment. We could turn it off with 'autoescape' => false but this is rarely a good idea in HTML templates.

$ php escaping.php
<p>&lt;script&gt;alert(&quot;pwned&quot;)&lt;/script&gt; &amp; &lt;b&gt;bold&lt;/b&gt;</p>
<p><em>Gardener</em> from Bratislava</p>
<p>Gardener from Bratislava</p>

<a href="/search?q=twig%20%26%20php">Search</a>
<input value="&lt;script&gt;alert&#x28;&quot;pwned&quot;&#x29;&lt;&#x2F;script&gt;&#x20;&amp;&#x20;&lt;b&gt;bold&lt;&#x2F;b&gt;">
<script>
    let msg = 'twig\u0020\u0026\u0020php';
</script>

<p><em>Gardener</em> from Bratislava</p>

Template inheritance

Template inheritance is the most powerful feature of Twig. A base template defines the layout of a page with blocks, and child templates fill in or override these blocks.

inheritance.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

echo $twig->render('about.html.twig', ['company' => 'Example Ltd']);

We render the child template; Twig loads the base template automatically.

templates/base.html.twig
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My site{% endblock %}</title>
{% block stylesheets %}
    <link rel="stylesheet" href="/css/main.css">
{% endblock %}
</head>
<body>
<main>
{% block content %}{% endblock %}
</main>
<footer>{% block footer %}&copy; {{ company }}{% endblock %}</footer>
</body>
</html>

The base layout defines four blocks: title, stylesheets, content and footer. A block may have default content, which is used when a child template does not override it.

templates/about.html.twig
{% extends 'base.html.twig' %}

{% block title %}About - {{ parent() }}{% endblock %}

{% block stylesheets %}
{{ parent() }}
    <link rel="stylesheet" href="/css/about.css">
{% endblock %}

{% block content %}
    <h1>About us</h1>
    <p>We build web applications.</p>
{% endblock %}

The extends tag must be the first tag of a child template. The parent function renders the content of the block from the base template, so the child adds a stylesheet instead of replacing the default one. The footer block is not overridden and keeps its default content. A child template can be extended again, so we can build chains such as base, section layout and page.

$ php inheritance.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>About - My site</title>
    <link rel="stylesheet" href="/css/main.css">

    <link rel="stylesheet" href="/css/about.css">
</head>
<body>
<main>
    <h1>About us</h1>
    <p>We build web applications.</p>
</main>
<footer>&copy; Example Ltd</footer>
</body>
</html>

Including templates

The include tag renders another template in place. It is used for partials, small pieces of markup shared by several pages. A common convention is to prefix partials with an underscore.

includes.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$products = [
    ['name' => 'Keyboard', 'price' => 45],
    ['name' => 'Monitor', 'price' => 230],
];

echo $twig->render('products.html.twig', [
    'products' => $products,
    'currency' => 'EUR',
]);

We pass two products and a currency to the template.

templates/_product.html.twig
<div class="product">
    <h3>{{ product.name }}</h3>
    <p>{{ product.price }}{{ currency is defined ? ' ' ~ currency }}</p>
</div>

The partial renders a single product. The currency is printed only if the currency variable is defined.

templates/products.html.twig
{% for product in products %}
{% include '_product.html.twig' %}
{% endfor %}

{{ include('_product.html.twig', { product: products|first }, with_context = false) }}
{% include '_missing.html.twig' ignore missing %}

By default, the included template has access to all variables of the current template, including the loop variable product. The include function passes its own variables; with with_context = false the included template sees only these variables, so the currency is missing in the last product. The ignore missing option silently skips templates that do not exist.

$ php includes.php
<div class="product">
    <h3>Keyboard</h3>
    <p>45 EUR</p>
</div>
<div class="product">
    <h3>Monitor</h3>
    <p>230 EUR</p>
</div>

<div class="product">
    <h3>Keyboard</h3>
    <p>45</p>
</div>

Macros

Macros are reusable template functions. They are often used for form widgets or other repeated HTML fragments.

macros.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

echo $twig->render('login.html.twig', ['username' => 'jan']);

We render a login form.

templates/forms.html.twig
{% macro input(name, value = '', type = 'text') -%}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{%- endmacro %}

{% macro label(text, for) -%}
    <label for="{{ for }}">{{ text }}</label>
{%- endmacro %}

The template defines two macros. Macro arguments may have default values.

templates/login.html.twig
{% import 'forms.html.twig' as forms %}
{% from 'forms.html.twig' import label %}
<form method="post">
    {{ label('User name', 'username') }}
    {{ forms.input('username', username) }}
    {{ label('Password', 'password') }}
    {{ forms.input('password', type: 'password') }}
</form>

The import tag imports all macros of a template under a name, and from ... import imports selected macros. Named arguments let us skip optional arguments, as in type: 'password'.

$ php macros.php
<form method="post">
    <label for="username">User name</label>
    <input type="text" name="username" value="jan">
    <label for="password">Password</label>
    <input type="password" name="password" value="">
</form>

Global variables

Global variables are available in all templates. They are registered with the addGlobal method of the environment.

globals.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\ArrayLoader;

$loader = new ArrayLoader([
    'footer' => '{{ app_name }} {{ version }} | {{ year }}',
]);

$twig = new Environment($loader);
$twig->addGlobal('app_name', 'Inventory');
$twig->addGlobal('version', '2.4.1');
$twig->addGlobal('year', 2026);

echo $twig->render('footer') . "\n";
echo $twig->render('footer', ['version' => '3.0-beta']) . "\n";

Variables passed to render override the globals of the same name, as we can see in the second call.

$ php globals.php
Inventory 2.4.1 | 2026
Inventory 3.0-beta | 2026

Custom filters, functions and tests

We can add our own filters, functions and tests with the TwigFilter, TwigFunction and TwigTest classes. They take a name and a PHP callable. (The old Twig_Filter-style class names of Twig 1 no longer exist.)

custom.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$twig->addFilter(new TwigFilter('price', function (float $value, string $currency = 'EUR'): string {
    return number_format($value, 2, '.', ' ') . ' ' . $currency;
}));

$twig->addFilter(new TwigFilter('excerpt', function (string $text, int $words = 5): string {
    $parts = preg_split('/\s+/', trim($text));

    if (count($parts) <= $words) {
        return $text;
    }

    return implode(' ', array_slice($parts, 0, $words)) . '...';
}));

$twig->addFunction(new TwigFunction('icon', function (string $name): string {
    return sprintf('<i class="icon icon-%s"></i>', htmlspecialchars($name));
}, ['is_safe' => ['html']]));

$twig->addTest(new TwigTest('palindrome', function (string $word): bool {
    $word = mb_strtolower($word);

    return $word === implode('', array_reverse(mb_str_split($word)));
}));

echo $twig->render('custom.html.twig', [
    'price' => 1249.5,
    'text' => 'Twig is a modern template engine for PHP with a concise syntax',
    'words' => ['level', 'twig', 'Radar', 'kayak'],
]);

The price filter formats a number with a currency and excerpt shortens a text to the given number of words. The first argument of a filter callable is the filtered value; the other arguments come from the parentheses in the template.

$twig->addFunction(new TwigFunction('icon', function (string $name): string {
    return sprintf('<i class="icon icon-%s"></i>', htmlspecialchars($name));
}, ['is_safe' => ['html']]));

The icon function returns HTML markup. The is_safe option tells Twig that the output is safe HTML and must not be escaped. The function escapes its input itself.

$twig->addTest(new TwigTest('palindrome', function (string $word): bool {

A test is a callable returning a boolean. The palindrome test uses multibyte functions, so it works with accented letters too.

templates/custom.html.twig
<p>{{ price|price }}, {{ price|price('USD') }}</p>
<p>{{ text|excerpt }}</p>
<p>{{ text|excerpt(8) }}</p>
<p>{{ icon('home') }} Home</p>

<ul>
{% for word in words %}
    <li>{{ word }} {{ word is palindrome ? 'is' : 'is not' }} a palindrome</li>
{% endfor %}
</ul>

The template uses the new filters, function and test in the same way as the built-in ones.

$ php custom.php
<p>1 249.50 EUR, 1 249.50 USD</p>
<p>Twig is a modern template...</p>
<p>Twig is a modern template engine for PHP...</p>
<p><i class="icon icon-home"></i> Home</p>

<ul>
    <li>level is a palindrome</li>
    <li>twig is not a palindrome</li>
    <li>Radar is a palindrome</li>
    <li>kayak is a palindrome</li>
</ul>

Extensions with attributes

In larger applications, custom filters and functions are grouped into extensions. Since Twig 3.21, we can mark ordinary PHP methods with the AsTwigFilter, AsTwigFunction and AsTwigTest attributes and register the class with the AttributeExtension.

src/AppExtension.php
<?php

namespace App;

use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;
use Twig\Attribute\AsTwigTest;

class AppExtension
{
    #[AsTwigFilter('mask_email')]
    public static function maskEmail(string $email): string
    {
        [$user, $domain] = explode('@', $email, 2);

        return $user[0] . str_repeat('*', strlen($user) - 1) . '@' . $domain;
    }

    #[AsTwigFunction('reading_time')]
    public static function readingTime(string $text, int $wpm = 200): string
    {
        $minutes = max(1, (int) ceil(str_word_count($text) / $wpm));

        return $minutes . ' min read';
    }

    #[AsTwigTest('weekend')]
    public static function isWeekend(\DateTimeInterface $date): bool
    {
        return $date->format('N') >= 6;
    }
}

The class defines a filter which masks the user part of an e-mail address, a function which estimates the reading time of a text, and a test for weekend dates. The methods are static, so Twig calls them without creating an instance. For non-static methods, the class has to be registered with a runtime loader.

attribute_extension.php
<?php

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/src/AppExtension.php';

use App\AppExtension;
use Twig\Environment;
use Twig\Extension\AttributeExtension;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);
$twig->addExtension(new AttributeExtension(AppExtension::class));

$article = [
    'title' => 'Twig templates',
    'author' => 'roger.roe@example.com',
    'body' => str_repeat('word ', 450),
    'published' => new DateTimeImmutable('2026-11-14'),
];

echo $twig->render('article.html.twig', ['article' => $article]);

The AttributeExtension reads the attributes of the given class. The older way of writing extensions, a class extending AbstractExtension with getFilters and getFunctions methods, still works.

templates/article.html.twig
<h1>{{ article.title }}</h1>
<p>By {{ article.author|mask_email }}, {{ reading_time(article.body) }}</p>
<p>Published on a {{ article.published is weekend ? 'weekend' : 'weekday' }}</p>

The template uses the extension. November 14, 2026 is a Saturday.

$ php attribute_extension.php
<h1>Twig templates</h1>
<p>By r********@example.com, 3 min read</p>
<p>Published on a weekend</p>

The string extension

Besides the core, Twig has official extra extensions installed as separate packages: twig/string-extra, twig/intl-extra (dates, numbers and currencies formatted for a locale; needs the intl PHP extension), twig/html-extra, twig/markdown-extra and others. The string extension is based on the Symfony String component.

$ composer require twig/string-extra
string_extra.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Extra\String\StringExtension;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);
$twig->addExtension(new StringExtension());

echo $twig->render('string_extra.txt.twig', [
    'title' => 'Žltý kôň: Twig & PHP templates',
    'text' => 'Twig is a modern template engine for PHP with a concise syntax',
]);

We register the StringExtension. In Symfony applications, the extra extensions are registered automatically by the twig/extra-bundle.

templates/string_extra.txt.twig
{{ title|slug }}
{{ title|slug('_')|lower }}
{{ text|u.truncate(25, '...') }}
{{ text|u.truncate(25, '...', false) }}
{{ text|u.wordwrap(30) }}
{{ 'user_profile_page'|u.camel }}
{{ 'UserProfilePage'|u.snake }}
{{ 'apple'|plural }} {{ 'children'|singular }}

The slug filter creates URL-friendly strings and transliterates accented letters. The u filter wraps the string in a Symfony UnicodeString object, so we can call its methods, such as truncate, wordwrap, camel or snake. By default, truncate cuts the text at the given length including the ellipsis; with false as the third argument it keeps the last word whole. The plural and singular filters inflect English words.

$ php string_extra.php
Zlty-kon-Twig-PHP-templates
zlty_kon_twig_php_templates
Twig is a modern templ...
Twig is a modern template...
Twig is a modern template
engine for PHP with a concise
syntax
userProfilePage
user_profile_page
apples child

Dates

The date filter formats dates, the date_modify filter modifies them, and the date function converts a value to a DateTime object. Dates can be strings, timestamps or DateTimeInterface objects.

dates.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Extension\CoreExtension;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$core = $twig->getExtension(CoreExtension::class);
$core->setTimezone('Europe/Bratislava');
$core->setDateFormat('j. n. Y H:i', '%a days');

$users = [
    ['name' => 'John Doe', 'created_at' => '2019-03-11 08:15:00 UTC'],
    ['name' => 'Lucy Smith', 'created_at' => '2024-07-02 17:40:00 UTC'],
];

echo $twig->render('dates.txt.twig', [
    'users' => $users,
    'today' => new DateTimeImmutable('2026-11-14 10:00:00 UTC'),
]);

The default time zone and date format are set on the CoreExtension. The second argument of setDateFormat is the default format for date intervals. We pass a fixed date as today instead of the current time, so the output does not change.

templates/dates.txt.twig
{% for user in users %}
{{ user.name }}
    created: {{ user.created_at|date }}
    in UTC: {{ user.created_at|date('Y-m-d H:i', 'UTC') }}
    weekday: {{ user.created_at|date('l') }}
    member for: {{ date(user.created_at).diff(today)|date }}
    status: {{ date(user.created_at) < today|date_modify('-5 years') ? 'senior' : 'regular' }} user
{% endfor %}

Next week: {{ today|date_modify('+1 week')|date('Y-m-d') }}
Timestamp: {{ today|date('U') }}

The date filter uses the PHP date format characters and converts the date to the default time zone; the second argument overrides the time zone. The diff method of DateTime returns a DateInterval, which the date filter formats with the interval format. We compare dates with the usual comparison operators.

Lucy's account is 864 full days old, not 865, because it was created at 17:40 and the reference time is 10:00. To compare with the current time, we would write date() or date('-5 years').

$ php dates.php
John Doe
    created: 11. 3. 2019 09:15
    in UTC: 2019-03-11 08:15
    weekday: Monday
    member for: 2805 days
    status: senior user
Lucy Smith
    created: 2. 7. 2024 19:40
    in UTC: 2024-07-02 17:40
    weekday: Tuesday
    member for: 864 days
    status: regular user

Next week: 2026-11-21
Timestamp: 1794650400

Enums

Twig works with PHP enums. The enum function returns an enum and enum_cases returns all its cases.

src/Status.php
<?php

namespace App;

enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function label(): string
    {
        return ucfirst($this->value);
    }
}

This is a backed enum with a label method.

enums.php
<?php

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/src/Status.php';

use App\Status;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);

$posts = [
    ['title' => 'Twig basics', 'status' => Status::Published],
    ['title' => 'Twig macros', 'status' => Status::Draft],
    ['title' => 'Twig 1.x notes', 'status' => Status::Archived],
];

echo $twig->render('enums.html.twig', ['posts' => $posts]);

We pass posts whose status is an enum case.

templates/enums.html.twig
<select name="status">
{% for status in enum_cases('App\\Status') %}
    <option value="{{ status.value }}">{{ status.label }}</option>
{% endfor %}
</select>

<ul>
{% for post in posts %}
    <li>{{ post.title }} ({{ post.status.name }})
        {{- post.status is same as(enum('App\\Status').Published) ? ' *' }}</li>
{% endfor %}
</ul>

<p>{{ constant('App\\Status::Draft').value }}</p>

The enum_cases function generates the options of a select box. On a case, status.value and status.name read the enum properties and status.label calls the method. The same as test compares the status with an enum case. Note that the backslash in the class name must be doubled in a Twig string. The constant function also returns enum cases and class constants.

$ php enums.php
<select name="status">
    <option value="draft">Draft</option>
    <option value="published">Published</option>
    <option value="archived">Archived</option>
</select>

<ul>
    <li>Twig basics (Published) *</li>
    <li>Twig macros (Draft)</li>
    <li>Twig 1.x notes (Archived)</li>
</ul>

<p>draft</p>

Error handling

Twig throws exceptions derived from Twig\Error\Error. A SyntaxError is thrown when a template cannot be compiled, a LoaderError when a template cannot be found, and a RuntimeError when rendering fails.

errors.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Error\Error;
use Twig\Loader\ArrayLoader;

$loader = new ArrayLoader([
    'undefined' => 'Hello {{ nme }}!',
    'syntax' => "<p>{{ name }}</p>\n{% if name %}\n<p>Hi</p>\n",
    'filter' => '{{ name|reverse|shout }}',
    'parent' => "{% extends 'layout' %}",
]);

$twig = new Environment($loader, ['strict_variables' => true]);

foreach (['undefined', 'syntax', 'filter', 'parent', 'missing'] as $name) {
    try {
        echo $twig->render($name, ['name' => 'Jan']), "\n";
    } catch (Error $e) {
        printf("%s: %s\n", (new ReflectionClass($e))->getShortName(), $e->getRawMessage());
        printf("    template: %s, line: %d\n", $e->getSourceContext()?->getName() ?? '-',
            $e->getTemplateLine());
    }
}

$lenient = new Environment($loader);
echo '[', $lenient->render('undefined', ['name' => 'Jan']), "]\n";

The exception knows the name of the template and the line where the error occurred. The getRawMessage method returns the message without this information.

$twig = new Environment($loader, ['strict_variables' => true]);

By default, Twig silently prints undefined variables and attributes as null, so a typo in a variable name goes unnoticed. With strict_variables set to true, Twig throws an exception instead. This option should be turned on at least during development. The last line of the output shows the default, lenient behaviour.

$ php errors.php
RuntimeError: Variable "nme" does not exist.
    template: undefined, line: 1
SyntaxError: Unexpected end of template.
    template: syntax, line: 4
SyntaxError: Unknown "shout" filter.
    template: filter, line: 1
LoaderError: Template "layout" is not defined.
    template: parent, line: 1
LoaderError: Template "missing" is not defined.
    template: -, line: -1
[Hello !]

Environment options and caching

Twig compiles templates to PHP classes. Without a cache, every template is compiled on each request. In production, we set the cache option to a writable directory.

options.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');

$twig = new Environment($loader, [
    'cache' => __DIR__ . '/cache',
    'auto_reload' => true,
    'debug' => true,
    'strict_variables' => true,
]);

$twig->addExtension(new DebugExtension());

$user = ['name' => 'Roger Roe', 'langs' => ['PHP', 'Go']];

echo $twig->render('debug.txt.twig', ['user' => $user]);

The cache option enables the compilation cache. With auto_reload, Twig recompiles a template when its source changes; this is convenient in development and turned off in production for speed. The debug option enables debugging features; together with the DebugExtension it gives us the dump function.

templates/debug.txt.twig
{{ dump(user) }}

The dump function prints the contents of a variable. Without arguments, it dumps all variables of the template. Symfony applications replace it with the dump function of the VarDumper component, which produces nicer output.

$ php options.php
array(2) {
  ["name"]=>
  string(9) "Roger Roe"
  ["langs"]=>
  array(2) {
    [0]=>
    string(3) "PHP"
    [1]=>
    string(2) "Go"
  }
}
$ find cache -type f
cache/8b/8b1ee44ff2ac0049e89bdcb06aaea87d.php

Plain text and other formats

HTML escaping would corrupt plain text e-mails or other non-HTML documents. With the name autoescape strategy, Twig chooses the escaping from the template's file extension: HTML for .html.twig, JavaScript for .js.twig and .json.twig, CSS for .css.twig and no escaping for .txt.twig.

notification.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\FilesystemLoader;

$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader, ['autoescape' => 'name']);

$data = [
    'name' => 'Tom & Jerry',
    'items' => [
        ['title' => 'Cheese <aged>', 'qty' => 2, 'price' => 4.5],
        ['title' => 'Milk', 'qty' => 1, 'price' => 1.2],
    ],
];

echo $twig->render('emails/order.txt.twig', $data);
echo "----\n";
echo $twig->render('emails/order.html.twig', $data);
echo "----\n";
echo $twig->render('emails/order.json.twig', $data), "\n";

We render an order confirmation in three formats. The data contains the & and < characters.

templates/emails/order.txt.twig
Dear {{ name }},

thank you for your order:
{% for item in items %}
  {{ '%-16s %2d x %5.2f'|format(item.title, item.qty, item.price) }}
{% endfor %}
Total: {{ items|reduce((sum, i) => sum + i.qty * i.price, 0)|number_format(2) }} EUR

The text version prints the data unchanged. The format filter aligns the items into columns.

templates/emails/order.html.twig
<p>Dear {{ name }},</p>
<ul>
{% for item in items %}
    <li>{{ item.title }}: {{ item.qty }} x {{ item.price }}</li>
{% endfor %}
</ul>

The HTML version escapes the special characters.

templates/emails/order.json.twig
{"customer": "{{ name }}", "items": {{ items|length }}}

The JSON template is escaped with the JavaScript strategy, which encodes special characters as \uXXXX sequences. The result is valid JSON. To create complex JSON, it is easier to use the json_encode filter.

$ php notification.php
Dear Tom & Jerry,

thank you for your order:
  Cheese <aged>     2 x  4.50
  Milk              1 x  1.20
Total: 10.20 EUR
----
<p>Dear Tom &amp; Jerry,</p>
<ul>
    <li>Cheese &lt;aged&gt;: 2 x 4.5</li>
    <li>Milk: 1 x 1.2</li>
</ul>
----
{"customer": "Tom\u0020\u0026\u0020Jerry", "items": 2}

Sandbox

Sometimes users write their own templates, for example for e-mail notifications in a web application. Such templates cannot be trusted. The sandbox restricts the tags, filters, functions, methods and properties a template may use. Since Twig 3.29, the Twig\Sandbox\Sandbox class renders untrusted templates in a dedicated environment.

sandbox.php
<?php

require __DIR__ . '/vendor/autoload.php';

use Twig\Environment;
use Twig\Loader\ArrayLoader;
use Twig\Sandbox\Sandbox;
use Twig\Sandbox\SecurityError;
use Twig\Sandbox\SecurityPolicy;

class User
{
    public function __construct(public string $login, public string $password) {}
}

$tags = ['if', 'for'];
$filters = ['upper', 'escape'];
$methods = [];
$properties = [User::class => ['login']];
$functions = [];

$policy = new SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$policy->setStrict(true);

$sandbox = new Sandbox(new Environment(new ArrayLoader()), $policy);

$userTemplates = [
    'Hello {{ name|upper }}!',
    '{% for c in colours %}{{ c }} {% endfor %}',
    '{{ name|reverse }}',
    "{% include 'secret.twig' %}",
    '{{ max(1, 2) }}',
    '{{ user.password }}',
];

foreach ($userTemplates as $source) {
    try {
        $template = $sandbox->createTemplate($source);
        echo $template->render([
            'name' => 'Jan',
            'colours' => ['red', 'green'],
            'user' => new User('jan', 's3cr3t'),
        ]), "\n";
    } catch (SecurityError $e) {
        echo 'Rejected: ', $e->getRawMessage(), "\n";
    }
}

The security policy lists everything the templates may use. The template may read the login property of a User object, but not its password. The Sandbox class requires a strict policy and a new environment that is used only for the untrusted templates.

$filters = ['upper', 'escape'];

The escape filter must be allowed; autoescaping adds it to every printed expression. Note that the 1..3 range operator calls the range function, which must be allowed too.

$template = $sandbox->createTemplate($source);

The createTemplate method compiles a template from a string. The tags, filters and functions used in the template are checked before it starts rendering; methods and properties are checked when they are accessed. In both cases, render throws a SecurityError.

$ php sandbox.php
Hello JAN!
red green 
Rejected: Filter "reverse" is not allowed.
Rejected: Tag "include" is not allowed.
Rejected: Function "max" is not allowed.
Rejected: Calling "password" property on a "User" object is not allowed.

Symfony example

Twig is the template engine of the Symfony framework. In this example, we create a small Symfony application with two pages.

$ composer create-project symfony/skeleton twigapp
$ cd twigapp
$ composer require twig
$ composer require --dev symfony/maker-bundle
$ php bin/console make:controller HomeController

We create a new Symfony skeleton application and install the Twig bundle. The twig alias installs the symfony/twig-bundle and twig/extra-bundle packages and creates the templates directory with a base layout. The maker bundle generates a controller with a template.

src/Controller/HomeController.php
<?php

namespace App\Controller;

use Symfony\Bridge\Twig\Attribute\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class HomeController extends AbstractController
{
    #[Route('/', name: 'app_home')]
    public function index(): Response
    {
        $words = ['sky', 'blue', 'cloud', 'symfony', 'forest'];

        return $this->render('home/index.html.twig', [
            'words' => $words,
        ]);
    }

    #[Route('/hello/{name}', name: 'app_hello')]
    #[Template('home/hello.html.twig')]
    public function hello(string $name): array
    {
        return ['name' => $name];
    }
}

The routes are defined with the Route attribute. The index action renders a template with the render method of the AbstractController. The hello action uses the Template attribute; it returns just an array of variables and Symfony renders the given template with them.

templates/base.html.twig
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}Welcome!{% endblock %}</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>

We replace the generated base layout with a simpler one.

templates/home/index.html.twig
{% extends 'base.html.twig' %}

{% block title %}Home page{% endblock %}

{% block body %}
<h2>List of words</h2>

<ul>
{% for word in words %}
    <li>{{ word }}</li>
{% endfor %}
</ul>

<a href="{{ path('app_hello', { name: 'Peter' }) }}">Say hello</a>
{% endblock %}

The home page lists the words. The path function, provided by the Symfony Twig bridge, generates the URL of a route from its name and parameters.

templates/home/hello.html.twig
{% extends 'base.html.twig' %}

{% block title %}Hello {{ name }}{% endblock %}

{% block body %}
<p>Hello {{ name }}!</p>
<p>Environment: {{ app.environment }}, route: {{ app.current_route }}</p>
{% endblock %}

Symfony adds the app global variable to all templates. It gives access to the request, the session, the current user, the environment and the current route.

$ php -S localhost:8000 -t public

We start the PHP built-in web server with the public directory as the document root. With the Symfony CLI we could use symfony server:start instead. In another terminal, we list the routes with the debug:router command and request the two pages with curl. The _preview_error route is added by the framework in the development environment.

$ php bin/console debug:router
 ---------------- -------- -------------------------- 
  Name             Method   Path                      
 ---------------- -------- -------------------------- 
  _preview_error   ANY      /_error/{code}.{_format}  
  app_home         ANY      /                         
  app_hello        ANY      /hello/{name}             
 ---------------- -------- -------------------------- 
$ curl localhost:8000/
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>
<h2>List of words</h2>

<ul>
    <li>sky</li>
    <li>blue</li>
    <li>cloud</li>
    <li>symfony</li>
    <li>forest</li>
</ul>

<a href="/hello/Peter">Say hello</a>
</body>
</html>
$ curl localhost:8000/hello/Lucy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Lucy</title>
</head>
<body>
<p>Hello Lucy!</p>
<p>Environment: dev, route: app_hello</p>
</body>
</html>

Source

Twig documentation

Twig for template designers

Twig for developers

Creating and using templates in Symfony

In this article we have used Twig to generate HTML and text documents from templates and data. We covered the syntax, filters, tests, loops, inheritance, includes, macros, escaping, custom extensions, the sandbox and Twig in a Symfony application. Read also the Composer and autoloading, PHP arrow functions and PHP Faker tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.