Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 62 ยท Templates with Twig

Twig Basics

Learn Twig, Symfony's template engine: printing with {{ }}, tags with {% %}, comments, variables, filters, if and for, and how auto-escaping protects you.

A controller decides what to show; a template decides how it looks. Symfony's template engine is Twig, a small language designed for exactly this job. It is concise, safe by default (output is escaped), and deliberately limited: a template can print values, loop and branch, but it cannot run arbitrary PHP or touch your database. That limit keeps logic in your PHP code and presentation in your templates.

This lesson introduces the whole core of the language: the three kinds of delimiters, variables and dot access, filters, if, for and set. Because Twig is a Composer package that cannot run on this site, the runnable examples use a tiny Twig-like engine written in plain PHP. It follows the same ideas so you can see how a template turns into HTML. Real Twig syntax appears in read-only blocks.

Install and render

In a Symfony project, Twig comes with composer require twig. Templates live in the templates/ folder and use the .html.twig extension. A controller renders one with render() from AbstractController:

PHP
// src/Controller/ProductController.php (real Symfony, read-only)
namespace App\Controller;

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

final class ProductController extends AbstractController
{
    #[Route('/products', name: 'product_index')]
    public function index(): Response
    {
        return $this->render('product/index.html.twig', [
            'title' => 'Our products',
            'products' => [
                ['name' => 'desk lamp', 'stock' => 4],
                ['name' => 'notebook', 'stock' => 0],
            ],
        ]);
    }
}

The array is the template's context: every key becomes a variable inside the template.

Three kinds of delimiters

Twig has exactly three pieces of syntax:

Syntax Purpose Example
{{ ... }} Print the result of an expression {{ title }}
{% ... %} Do something: loops, conditions, assignments {% if user %}
{# ... #} Comment; never reaches the output {# TODO #}

Everything outside the delimiters is plain text copied to the output. A template is therefore just an HTML file with a few holes in it.

TWIG
{# templates/product/index.html.twig (real Twig, read-only) #}
<h1>{{ title|upper }}</h1>

<ul>
{% for product in products %}
    <li>{{ loop.index }}. {{ product.name|capitalize }}
        {% if product.stock == 0 %}(sold out){% endif %}</li>
{% else %}
    <li>No products yet.</li>
{% endfor %}
</ul>

Variables and dot access

You print a variable by naming it. To reach inside an array or object, use a dot: product.name. The dot is a convenience that tries several things in order. For product.name, Twig checks whether product is an array with the key name; if not, whether it is an object with a public property name; then a method name(), getName(), isName() or hasName(). That is why you write user.name in a template whether name is an array key, a property or a getter on your entity.

If the variable does not exist, Twig's behaviour depends on a setting. With strict_variables enabled (the default in the dev and test environments of a Symfony project), a missing variable throws an error so you notice typos. In production a missing variable prints as empty. Use the default filter or the ?? operator when a value is truly optional: {{ user.nickname ?? 'guest' }}.

You can assign values with set:

TWIG
{# real Twig, read-only #}
{% set total = products|length %}
{% set greeting = 'Hello, ' ~ user.name %}
<p>{{ greeting }}: you have {{ total }} products.</p>

Notice ~, Twig's string concatenation operator. A + is arithmetic only.

Filters

A filter transforms a value. You apply one with the pipe character, and you can chain them left to right:

TWIG
{# real Twig, read-only #}
{{ 'twig basics'|title }}                {# Twig Basics #}
{{ name|lower|capitalize }}
{{ items|length }}
{{ comment|default('No comment') }}
{{ tags|join(', ') }}
{{ price|number_format(2, '.', ',') }}

Some filters take arguments in parentheses. The next lesson on functions, filters and tests lists the built-in ones. For now, remember the shape: value|filter(arguments).

Control structures

if, elseif and else branch. Conditions use and, or, not, comparison operators, and the useful in operator:

TWIG
{# real Twig, read-only #}
{% if user.isAdmin %}
    <a href="/admin">Admin</a>
{% elseif user %}
    <p>Welcome back.</p>
{% else %}
    <a href="/login">Log in</a>
{% endif %}

{% if 'sale' in tags and not product.archived %}On sale!{% endif %}

for loops over arrays and other iterables. Inside a loop, Twig provides a loop variable with loop.index (starting at 1), loop.index0, loop.first, loop.last and loop.length. A for loop may have an else branch that runs when the sequence is empty, replacing a separate if check. You can loop over keys and values with for key, value in map, and over numbers with the range operator: for i in 1..5.

flowchart LR
    T["Template source<br/>(.html.twig)"] --> L["Lexer<br/>tokens"]
    L --> P["Parser<br/>tree of nodes"]
    P --> C["Compiler<br/>PHP class"]
    C --> K["Cache<br/>var/cache"]
    K --> R["render(context)"]
    R --> H["HTML string"]

Real Twig compiles each template to a PHP class once and caches it; later requests just run that class.

A Twig-like engine you can run

The engine below is a stand-in: far smaller than Twig, but it uses the same pipeline. It splits the source into text and tags, builds a tree of nodes (print, if, for, set), then walks the tree with a context array. It supports comments, dot access, a few filters, loop, else and raw. Real Twig compiles to PHP instead of walking a tree, but a tree is easier to read.

PHP A mini Twig-like engine (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the output: the comment vanished, title was upper-cased, capitalize fixed DESK lamp, the for ... else branch handled the empty list, and {{ note }} printed &lt;b&gt; while {{ note|raw }} printed real tags. That last pair is auto-escaping, which deserves its own section.

Auto-escaping

By default, Twig escapes every printed value for HTML. If a user types <script> into a comment field, {{ comment }} prints &lt;script&gt;, so the browser shows text instead of running code. This is your main defence against cross-site scripting (XSS) in templates.

The raw filter turns escaping off for one value: {{ html|raw }}. Use it only for HTML you built and trust (for example the output of a Markdown converter that you sanitize). Never use it on user input. Twig also escapes for other contexts when you ask, such as {{ value|e('js') }} or {{ value|e('url') }}, and the Symfony Twig bundle picks the right strategy from the template file name (.html.twig escapes for HTML).

Attribute lookup order

The dot lookup is subtle enough to deserve a demonstration. This stand-in implements the same search order Twig uses (array key, then property, then method names) so you can see which one wins.

PHP How product.name is looked up (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Because of this lookup, you can refactor an array into an object (or a public property into a getter) without touching your templates.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which delimiter prints the value of an expression?

    Double curly braces print. {% %} runs statements such as if and for, and {# #} is a comment.
  2. 2. What does {{ comment }} output if comment contains <script>?

    Twig auto-escapes printed values for HTML. Use |raw only for trusted HTML.
  3. 3. How does Twig resolve product.name when product is an object?

    The dot is flexible: array key first, then property, then several method names.
  4. 4. What is the Twig operator for string concatenation?

    Twig uses the tilde, for example 'Hello, ' ~ name. The plus sign is for numbers.
  5. 5. What does the else branch of a for loop do?

    for ... else ... endfor shows alternative content for an empty sequence.

Summary

  • Twig has three delimiters: {{ }} prints, {% %} performs statements, {# #} comments.
  • Variables come from the context array passed to render(); the dot reaches array keys, properties and getters.
  • Filters transform values with | and chain left to right; ~ concatenates strings.
  • if, elseif, else, for (with loop and else) and set cover most template logic.
  • Output is HTML-escaped by default; |raw is for trusted HTML only.
  • The runnable engine is a stand-in; real Twig compiles templates to cached PHP classes.

Next up: Layouts, Blocks and Includes.