Reusing Twig templates
If we look at our themes
templates folder, we can see that we have created quite a few Twig templates. While having an abundance of Twig templates is not necessarily a bad thing, it does become a little bit harder to manage our code.
One powerful feature of Twig templates is that they allow us to address this by extending or sharing markup between each template. This is great for global sections of markup. For example, the header and footer of our page never change, so why have the same markup in both page
templates?
Using extends to share layouts
Twig {% extends %}
allows us to share markup between templates by extending a template from another one. In our case, we could use this Twig function by extending the page.html.twig
template from our page--front.html.twig
template.
Begin by opening up the page--front.html.twig
template in our favorite editor and add the following markup to the very top of our page:
New markup
{% extends 'themes/octo/templates/page.html...