The extends
tag allows to extend a twig
template from another one in order to modify it by changing or adding features.
By extending a parent template, a child template inherits all content of the parent template.
This allows a child template to customize the parts of the parent template.
To better understande the concept, let’s define a parent template which we will call base.twig:
base.twig
<html>
<head>
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<div id="content">
{% block content %}
Default content goes here.
{% endblock %}
</div>
<div id="footer">
{% block footer %}
Default footer content
{% endblock %}
</div>
</body>
</html>
In this example, the block tags define three blocks (title, content and footer) that child templates can override or fill in.
All the block
tag does is to tell the template engine that a child template may override those parts of the template.
A child template might look like this:
child.twig
{% extends './base.twig' %}
{% block title %} Home {% endblock %}
{% block content %}
Home page content.
{% endblock %}
The extends
tag is the key here, and it tells the template engine that this template inherits everything from parent template.
When the template system evaluates this template, it first locates the parent.
The extends
tag must be the first tag in the template.
There is no limit to how long of an inheritance chain you can create, i.e. a child template can itself have a child template.
A lot of potential comes from this fact because you can create a hierarchy of templates to minimize how much content you have to write on the lower levels.
Note that since the child template doesn’t define the footer block, the value from the parent template is used instead.
You can’t define multiple block tags with the same name in the same template.
This limitation exists because a block tag works in "both" directions.
That is, a block tag doesn’t just provide a hole to fill - it also defines the content that fills the hole in the parent.
If there were two block tags with the same name in a template, that template’s parent wouldn’t know which one of the blocks' content to use.
<html>
<head>
<title> Home </title>
</head>
<body>
<div id="content">
Home page content.
</div>
<div id="footer">
Default footer content
</div>
</body>
</html>