Extending or including - what is better in Twig?

后端 未结 5 980
执念已碎
执念已碎 2021-01-30 17:06

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

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 18:03

    It depends on what you're trying to accomplish. By extending a view, you're using the Decorator pattern. If you're familiar with Symfony 1, this is the same as having your layout.php file which outputs $sf_content. You use this method when you have a common html 'shell' you want to use across the project.

    Including a view on the other hand lets you inject one view in another.

    Let's say you have a personal site with 'about' and 'contact' pages. You would have 3 views: base.html.twig
    about.html.twig
    contact.html.twig

    base.html.twig contains the common HTML that your site uses across the board. This could include your header, navigation, footer etc (all the stuff that doesn't/shouldn't change across pages.)

    about.html.twig and contact.html.twig contain ONLY the HTML for those specific sections. Both of these views extend base.html.twig. This eliminates code duplication. If you want to make a change to the header, you just need to make the change in one place - base.html.twig.

    Now let's say you have some other piece of content you want to display on the 'about' and 'contact' pages (but not necessarily on other pages) - you could create a separate view for this and include it within about.html.twig and contact.html.twig.

    The docs don't actually recommend extending over including, they're two separate methods that should be used for specific purposes.

    Hope this helps!

提交回复
热议问题