Search code examples
phpsymfonytwigtemplate-engine

Extending or including - what is better in Twig?


Why Twig documentation recommends to use extending rather than including? Symfony 2 documentation says because "In Symfony2, we like to think about this problem differently: a template can be decorated by another one." but nothing more. It's just author's whim or something more? Thanks for help.


Solution

  • When to use inheritance:

    You have 50 pages sharing the same layout - you create a layout.twig as a parent, and each page extends that layout.twig. So the parent is the generic and the child is the specific.

    When to use include:

    Out of the 50 pages, there are 6 pages that share a chunk of HTML - you create a shared-chunk.twig and include it in those 6 pages.

    Another usage:

    You notice that your layout.twig is bit cluttered and you would like to modularize it, so you split sidebar.twig into a separate file and include it in layout.twig.

    Can you use include for the inheritance use-case:

    Sure, create chunks for header, footer and what have you, and use includes in each of the 50 pages. But that's wrong design as explained above.

    Can you use inheritance for the include use-case:

    Sure, create an empty block for the shared chunk in the parent layout.twig, and create a second level child layout-with-chunk.twig that extends layout.twig and fills in the chunk block, and the 6 pages in the above example that share the chunk can then extend layout-with-chunk.twig instead of layout.twig. But this again is wrong design because the chunk block is not shared by all children and shouldn't go into the base parent. Plus you have cluttered the inheritance tree.

    So:

    As explained above - it's a matter of design not programmability. It's not about: I can achieve this same result using a different programming technique, its about which usage is better design.