bg_image
header

Twig

What is Twig?

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.


Key Features of Twig

1. Simple Syntax with Placeholders ({{ }})

Twig uses double curly braces to output variables:

<p>Hello, {{ name }}!</p>

→ If name = "Max", the output will be:
"Hello, Max!"


2. Control Structures ({% %})

Twig supports if-else statements, loops, and other control structures.

If-Else

{% 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>

3. Template Inheritance

Twig supports "Base Layouts", similar to Laravel's Blade.

Parent Template (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.


4. Including Templates

You can include reusable components like a navbar or footer:

{% include 'partials/navbar.html.twig' %}

5. Filters & Functions

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") }}`

6. Security & Escaping

Twig automatically escapes HTML to prevent XSS attacks:

{{ "<script>alert('XSS');</script>" }}

→ Outputs: &lt;script&gt;alert('XSS');&lt;/script&gt;

To output raw HTML, use |raw:

{{ "<strong>Bold</strong>"|raw }}

7. Extensibility

  • Twig supports custom filters & functions.
  • You can use PHP objects and arrays directly inside Twig.

Random Tech

HHVM - HipHop Virtual Machine


HHVM_logo.svg.png