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 ...

Get Drupal 8: Enterprise Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.