Outputting variables
{{ variable }} <!-- auto-escaped -->
{{ variable|e }} <!-- explicit HTML escape -->
{{ variable|raw }} <!-- unescaped — use ONLY for trusted content -->
Conditionals
{% if user.is_admin %}
<a href="/admin">Admin Panel</a>
{% elseif user %}
<a href="/profile">My Profile</a>
{% else %}
<a href="/login">Log In</a>
{% endif %}
Loops
{% for post in posts %}
<article>
<h2>{{ post.title|e }}</h2>
<p>{{ post.excerpt|e }}</p>
</article>
{% else %}
<p>No posts yet.</p>
{% endfor %}
The {% else %} block runs if the loop had zero items.
Loop variables
{% for item in items %}
{{ loop.index }} <!-- 1, 2, 3... -->
{{ loop.index0 }} <!-- 0, 1, 2... -->
{{ loop.first }} <!-- true on first iteration -->
{{ loop.last }} <!-- true on last iteration -->
{{ loop.length }} <!-- total item count -->
{% endfor %}
Comments
{# This won't appear in the output #}
Filters
Transform output with the pipe | operator:
{{ title|upper }} <!-- "HELLO WORLD" -->
{{ title|lower }} <!-- "hello world" -->
{{ title|capitalize }} <!-- "Hello World" -->
{{ body|striptags }} <!-- strip HTML tags -->
{{ date|date("F j, Y") }} <!-- "May 25, 2026" -->
{{ text|length }} <!-- character count -->
{{ items|length }} <!-- array count -->
{{ "<b>bold</b>"|raw }} <!-- renders as HTML -->
Variables in templates
{% set greeting = "Hello, " ~ name %}
<p>{{ greeting }}</p>
{% set items = [1, 2, 3] %}
{% set config = { theme: "dark", lang: "en" } %}
Includes
Insert another template inline:
{% include "header.twig" %}
{% include "sidebar.twig" with { items: menu_items } %}
A real template: blog listing
{% extends "layout" %}
{% block content %}
<h1>{{ page_title }}</h1>
{% if posts|length > 0 %}
{% for post in posts %}
<article class="post">
<h2>
<a href="/blog/{{ post.slug }}">{{ post.title|e }}</a>
</h2>
<time>{{ post.created_at|date("M j, Y") }}</time>
<p>{{ post.excerpt|e }}</p>
</article>
{% endfor %}
{% if pagination.has_next %}
<a href="?page={{ pagination.page + 1 }}">Older posts</a>
{% endif %}
{% else %}
<p>No posts yet. Check back soon!</p>
{% endif %}
{% endblock %}
Next: Inheritance & Includes — build reusable layouts.