twig tutorial - Comparison of Include and Extends in Twig - twig php - twig template
Comparison of Include, Extends, Use, Macro, Embed
- There are various types of inheritance and code reuse in Twig:
Include
- The main goal is code reuse. Consider using header.html.twig & footer.html.twig inside base.html.twig as an example.
header.html.twig
base.html.twig
Extends
- The main goal is vertical inheritance. Consider extending base.html.twig inside homepage.html.twig and about.html.twig as an example.
base.html.twig
homepage.html.twig
about.html.twig
Use
- The main goal is horizontal reuse. Consider using sidebar.product.html.twig inside single.product.html.twig (extends product.layout.html.twig) and single.service.html.twig (extends 'service.layout.html.page') pages. (it's like macros, but for blocks)
sidebar.html.twig
single.product.html.twig
single.service.html.twig
Macro
- The main goal is having reusable markup across many templates with variables. Consider a function which gets some variables and outputs some markup.
profile.service.html.twig
Embed
- The main goal is block overriding. It has functionality of both Use & Include together. Consider embedding pagination.html.twig in product.table.html.twig & service.table.html.twig.
pagination.html.twig
product.table.html.twig
service.table.html.twig
Please note that embedded file (pagination.html.twig here) has access to the current context (min, max variables here). Also you may pass extra variables to the embedded file: