Twig is a powerful and flexible templating engine for PHP, commonly used in Symfony but also in other PHP projects. It helps separate logic from presentation and offers many useful features for frontend development.
{{ }}
)Twig uses double curly braces to output variables:
<p>Hello, {{ name }}!</p>
→ If name = "Max"
, the output will be:
"Hello, Max!"
{% %}
)Twig supports if-else statements, loops, and other control structures.
{% if user.isAdmin %}
<p>Welcome, Admin!</p>
{% else %}
<p>Welcome, User!</p>
{% endif %}
Loops (for
)
<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% endfor %}
</ul>
Twig supports "Base Layouts", similar to Laravel's Blade.
base.html.twig
)<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Page{% endblock %}</title>
</head>
<body>
<header>{% block header %}Default Header{% endblock %}</header>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
Child Template (page.html.twig
)
{% extends 'base.html.twig' %}
{% block title %}Homepage{% endblock %}
{% block content %}
<p>Welcome to my website!</p>
{% endblock %}
→ The blocks override the default content from the base template.
You can include reusable components like a navbar or footer:
{% include 'partials/navbar.html.twig' %}
Twig provides many filters to format content:
Filter | Beispiel | Ausgabe |
---|---|---|
upper |
`{{ "text" | upper }}` |
lower |
`{{ "TEXT" | lower }}` |
length |
`{{ "Hallo" | length }}` |
date |
`{{ "now" | date("d.m.Y") }}` |
Twig automatically escapes HTML to prevent XSS attacks:
{{ "<script>alert('XSS');</script>" }}
→ Outputs: <script>alert('XSS');</script>
To output raw HTML, use |raw
:
{{ "<strong>Bold</strong>"|raw }}