Twig Cheat Sheet for Symfony
The snippets below are for Twig 3 inside Symfony 7. The one that catches people is reading a POST value: it is app.request.request.get("page"), because Symfony's request object keeps POST data in a property called request. The shorter-looking app.request.parameter.get("page") is not an error and not a value: it prints nothing.
Tested on
Twig 3.30.0, symfony/twig-bridge 7.4.22 and symfony/http-foundation 7.4.23, on PHP 8.3.36, on 11/13/2026. I built a request for POST /form?page=3 with a POST field page=7, a cookie acceptCookies=yes and a session value page=S, then rendered each line below and read what came out. The framework's controller and listeners were not part of the test, so values that Symfony fills in for you (the locale, the logged-in user) are not covered here.
| You write | It printed |
|---|---|
{{ app.request.request.get("page") }} |
7 (POST) |
{{ app.request.parameter.get("page") }} |
nothing, no error |
{{ app.request.query.get("page") }} |
3 (GET) |
{{ app.request.cookies.get("acceptCookies") }} |
yes |
{{ app.request.cookies.has("nope") }} in an if |
false branch |
{{ app.session.get("page") }} |
S |
{{ app.request.session.get("page") }} |
S |
{{ app.request.headers.get("referer") }} |
the referer URL |
{{ app.request.query.get("missing") }} |
nothing |
Reading request values
{# $_POST #}
{{ app.request.request.get("page") }}
{# $_GET #}
{{ app.request.query.get("page") }}
{# $_COOKIE #}
{{ app.request.cookies.get("page") }}
{# $_SESSION #}
{{ app.session.get("page") }}
{# where the visitor came from; other headers work the same way #}
{{ app.request.headers.get("referer") }}
Show something only when a cookie exists:
{% if app.request.cookies.has('acceptCookies') %} Yes you accept cookies {% endif %}
Skip a block when a value was never defined, which avoids an error for unset values:
{# Skip the prototype if the form was submitted, else the fields show up twice #}
{% if form.contactInfoApp.address1 is not defined %}
Print HTML without escaping it. This is the one place the autoescaper steps aside, so use it only on markup you built yourself:
{% if formMessage is defined %}
{{ formMessage|raw }}
{% endif %}
With m set to <b>x</b>, {{ m|raw }} printed <b>x</b> and {{ m }} printed <b>x</b>. The autoescaping post covers where raw goes wrong.
Looping
loop.index counts from 1 and loop.index0 from 0. Run on a list of a, b, c, the loop below printed 1/3 first=1, 2/3 first=0, then 3/3 last=1, and the else branch printed empty for an empty list.
{% for comment in comments %}
Comment {{ loop.index }} of {{ loop.length }}: {{ comment.description }}
{% else %}
No comments yet.
{% endfor %}
To pick an item from an array by a key you hold in another variable, use the bracket form. It printed Mailing Address for arr = {1: "Mailing Address"} and k = 1, the same as the older attribute(arr, k) call:
{{ arr[k] }}
Defaults, filters and tests
Run on 11/17/2026 with Twig 3.30.0 inside a Symfony 7.4.23 project (PHP 8.3.36), with strict_variables on, which is the development default. Each line was rendered from a string template and the output is what is shown.
| You write | It printed |
|---|---|
{{ u|default("guest") }} with u never set |
guest |
{{ ""|default("empty") }} |
empty |
{{ 0|default("zero") }} |
0 (zero is not empty) |
{{ u ?? "anon" }} with u never set |
anon |
{{ u.name ?? "noname" }} |
noname |
{{ n > 1 ? "many" : "one" }} with n 2 |
many |
{{ s|upper }}, {{ s|title }}, {{ s|length }} for hello world |
HELLO WORLD, Hello World, 11 |
{{ l|join(", ") }} for a, b, c |
a, b, c |
{{ s|slice(0,3) }} |
hel |
{{ s|replace({"o":"0"}) }} |
hell0 w0rld |
{{ d|date("Y-m-d") }} for a DateTime |
2026-11-17 |
{{ 1234.5|number_format(2) }} |
1,234.50 |
{{ 1234.5|number_format(2, ",", ".") }} |
1.234,50 |
{{ l|sort|join(",") }} for 3, 1, 2 |
1,2,3 |
{{ l|reverse|join(",") }} for 3, 1, 2 |
2,1,3 (the list reversed as given, not sorted) |
{{ x is defined ? "def" : "undef" }} |
undef |
{{ n is empty }} for [] |
true |
{{ 4 is even }} |
true |
{{ "a" in l }} for ["a"] |
true |
{{ "abc" matches "/^a/" }} |
true |
With strict_variables on, printing a variable that was never set is an error: {{ nothing }} threw Variable "nothing" does not exist. default, ?? and is defined are the three ways to ask about a possibly missing value without that error. The strict_variables post shows how to turn the setting on and off.
Loops over keys and ranges:
{% for k, v in m %}{{ k }}={{ v }};{% endfor %} {# a=1;b=2; #}
{% for i in 1..3 %}{{ i }}{% endfor %} {# 123 #}
{% for i in range(0, 10, 5) %}{{ i }},{% endfor %} {# 0,5,10, #}
Setting values and wrapping a block in a filter:
{% set total = 3 + 4 %}{{ total }} {# 7 #}
{% apply upper %}shout{% endapply %} {# SHOUT #}
Escaping for other contexts. For the value <a href="x">T&C</a>:
| Filter | It printed |
|---|---|
| none (HTML autoescape) | <a href="x">T&C</a> |
e("url") |
%3Ca%20href%3D%22x%22%3ET%26C%3C%2Fa%3E |
striptags |
T&C (tags removed, then escaped) |
e("js") |
\u003Ca\u0020href\u003D\u0022x\u0022\u003ET\u0026C\u003C\/a\u003E |
A newline became <br /> through nl2br, and {{ o|json_encode|raw }} printed {"a":1,"b":2}.
Inheritance, includes and macros
Tested the same day, with these files in templates/:
{# base.html.twig #}
<main>{% block body %}base{% endblock %}</main>
{# child.html.twig #}
{% extends "base.html.twig" %}
{% block body %}[{{ parent() }}] child{% endblock %}
Rendering child.html.twig printed <main>[base] child</main>: parent() pulls in the block you are overriding.
An included template sees the including template's variables unless you say only. With part.html.twig holding part:{{ x|default("none") }}:
| You write | It printed |
|---|---|
{% include "part.html.twig" with {x:"given"} %} |
part:given |
{% include "part.html.twig" %} with no x anywhere |
part:none |
{% include "part.html.twig" with {x:"only"} only %} |
part:only |
A macro is a function for markup. With macros.html.twig holding {% macro tag(t) %}<b>{{ t }}</b>{% endmacro %}, this printed <b>hi</b>:
{% import "macros.html.twig" as m %}
{{ m.tag("hi") }}
Calling path("nope") for a route that does not exist threw Unable to generate a URL for the named route "nope" as such route does not exist, so a typo in a route name fails loudly instead of printing a bad link. To check every template for syntax errors without rendering them, run php bin/console lint:twig templates: it printed All 4 Twig files contain valid syntax, and after a file containing only {% if x %} was added it printed Unexpected end of template with the file and line, then 4 Twig files have valid syntax and 1 contain errors. To list the filters, functions and tests a project has, run php bin/console debug:twig; --filter=upper narrowed it to upper(string).
Rendering a template to a string
When you need rendered Twig as a value, for an email body or an AJAX fragment, ask the environment for it. The underscore class names in older guides, such as Twig_Loader_Filesystem, are gone: on Twig 3.30, class_exists('Twig_Loader_Filesystem') is false. This ran and returned Hi A, here:
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$twig = new Environment(new FilesystemLoader('/path/to/templates'), [
'cache' => '/path/to/compilation_cache',
]);
$html = $twig->render('index.html.twig', ['name' => 'A', 'set' => 'here']);
$twig->createTemplate('Hi {{ n }}')->render(['n' => 'inline']) returned Hi inline, for a template held in a string. Inside a Symfony service, inject the Twig\Environment instead of building one: render Twig outside a controller.
Debugging with dump
{% debug x %} is not a Twig tag: rendering it threw Unknown "debug" tag. The tool is dump, and it needs an extension registered. I tested two:
| Extension | Output of {{ dump(x) }} |
|---|---|
Twig's own Twig\Extension\DebugExtension, with debug on |
a plain var_dump of the value |
the same extension, with debug off |
an empty string |
Symfony's DumpExtension (symfony/twig-bridge), with debug on |
a collapsible dump, and the {% dump x %} tag also works |
| no extension | Unknown "dump" function |
{{ dump(variableForDumping) }}
Because debug off prints nothing, a stray dump() left in a template does not leak values in production, which is the reason to keep debug tied to the environment. I registered the extensions by hand in a plain Twig environment; how a full Symfony app wires them up was not part of the test.
An IDE that understands both Twig and YAML saves time here, because a single wrong indent or a tab character in a YAML config is the commonest reason an extension is not found.
– Aaron Belchamber (belchamber.us)