Twig basics
| 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