Twig basics

Contents
Print variables
Loops
Conditions
Include partials

Print variables

Twig prints expressions inside double curly braces. The controller passes the variables, and the template only displays them:

<h1>Hello, {{ name }}!</h1> <p>Your total is {{ total }}.</p>

Loops

Loop over lists with for. Each pass exposes one item under the loop variable:

<ul> {% for post in posts %} <li>{{ post.title }}</li> {% endfor %} </ul>

Conditions

Branch with if, elseif, and else. Tests like empty keep templates readable without numeric comparisons:

{% if posts is empty %} <p>No posts yet.</p> {% else %} <p>Enjoy the list.</p> {% endif %}

Include partials

Shared pieces like menus live in partial files. The include function renders another template inside the current one. This line loads templates/partials/_menu.html.twig:

<nav> {{ include("partials/_menu.html.twig") }} </nav>

Next: Twig advanced

Article author: Arthur Isaev

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: