Extending templates
This documentation needs work. See "Help improve this page" in the sidebar.
Extending a template means that you can use the contents of an existing template on your template and apply your own modifications to it.
Twig templates can be extended with the following syntax:
{% extends 'example.html.twig' %}
See more at https://symfony.com/doc/current/templates.html#template-inheritance-and-layouts
In Drupal we can see many examples that use extends
in core. e.g.
In core/modules/block/templates/block.html.twig we have:
<div{{ attributes }}>
{{ title_prefix }}
{% if label %}
<h2{{ title_attributes }}>{{ label }}</h2>
{% endif %}
{{ title_suffix }}
{% block content %}
{{ content }}
{% endblock %}
</div>
This is extended in web/core/modules/system/templates/block--local-actions-block.html.twig with the use of extends
e.g.
{% extends "block.html.twig" %}
{% block content %}
{% if content %}
<nav>{{ content }}</nav>
{% endif %}
{% endblock %}
Here everything is inherited from base template except for :
{% block content %}
{{ content }}
{% endblock %}
This is overridden with the following in the child template:
{% block content %}
{% if content %}
<nav>{{ content }}</nav>
{% endif %}
{% endblock %}
Drupal modules and themes are automatically namespaced. In this example, both these modules sit within the same core namespace, so they do not need to be prepended by the name of the module or theme.
To extend a template from another theme or module (e.g. here from the classy theme), use the machine name:
{% extends "@classy/block/block--system-menu-block.html.twig" %}
Or, if using Twig 3.0.0, introduced with Drupal 10.x you can now skip the path to the Twig file if the component is deeply nested in your namespace’s path. :
{% extends "@classy/block--system-menu-block.html.twig" %}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion