Template inheritance
Template inheritance is one of the most powerful features in Twig, allowing you to create a base template that can be extended by other templates. This promotes reusability and helps keep your code , making it easier to maintain and update your ShopWired theme.
How template inheritance works
Template inheritance in Twig is based on a parent-child relationship between templates. The parent template defines the overall structure, and the child templates can override specific sections of the parent template.
The `extends` tag
The extends
tag is used in a child template to indicate that it inherits from a parent template. The child template can then override specific blocks defined in the parent template.
{% extends 'templates/master.twig' %}
In this example, the child template extends master.twig
, meaning it will inherit the structure and content of master.twig
, but it can override specific blocks.
The `block` and `endblock` tags
The block
tag is used in the parent template to define sections that can be overridden in child templates. Each block
tag is given a name, and the child template can use the same name to override the block's content.
Parent template (master.twig
):
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<header>{% block header %}Default Header{% endblock %}</header>
<main>{% block content %}Default Content{% endblock %}</main>
<footer>{% block footer %}Default Footer{% endblock %}</footer>
</body>
</html>
Child template:
{% extends 'master.twig' %}
{% block title %}Custom Title{% endblock %}
{% block content %}
<h1>Welcome to my ShopWired store</h1>
<p>This is the custom content of the page.</p>
{% endblock %}
In this example, the child template overrides the title
and content
blocks defined in the parent template, while the header
and footer
blocks remain as defined in the parent.
Overriding blocks partially
In some cases, you may want to keep part of the parent's block content while adding your own content. You can achieve this by using the parent()
function within the block in the child template.
{% block content %}
{{ parent() }}
<p>Additional custom content.</p>
{% endblock %}
This will include the original content from the parent template’s content
block and append "Additional custom content."
Defining blocks in child templates
Child templates can also define new blocks that can be overridden by further child templates, making your templates even more modular.
{% extends 'master.twig' %}
{% block title %}Custom Title{% endblock %}
{% block content %}
<h1>Welcome to my ShopWired store</h1>
<p>This is the custom content of the page.</p>
{% block extra_content %}{% endblock %}
{% endblock %}
In this example, the extra_content
block is defined in the child template, which can then be overridden by another template that extends this child template.