What is twig template inheritance and how to use it?
Twig template inheritance is a powerful feature of the Twig templating engine (commonly used in Symfony and other PHP frameworks) that allows you to define a base template and then extend it in child templates. This encourages code reuse, maintainability, and clean separation of concerns in your templates.
How Template Inheritance Works:
1. Create a Base Template (base.html.twig
)
This template includes the HTML structure and defines blocks that child templates can override.
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
2. Extend the Base Template in a Child Template
You create a new template that extends the base and overrides one or more blocks.
{# home.html.twig #}
{% extends "base.html.twig" %}
{% block title %}Home{% endblock %}
{% block content %}
<p>Welcome on my awesome homepage.</p>
{% endblock %}
Benefits:
- DRY (Don’t Repeat Yourself) – Define the layout once.
- Maintainable – Changes in the layout affect all child templates.
- Clean Structure – Easy to read and follow.