Extending or including - what is better in Twig?

后端 未结 5 979
执念已碎
执念已碎 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条回答
  •  抹茶落季
    2021-01-30 18:08

    I liked Arms answer, but I think you missed what he said. Include and extend are different things: if you extend, you can change the parent, with an include you can not.

    E.g. I extend my base layout, like so:

    {% extends "layout/default.html" %}
    

    What extending give me now, is to use the blocks from the parent! You don't have that with an include. Now you can e.g. make a title specifically for every page:

    {% block title %}My title just for this page{% endblock %}
    

    Now, including gives you more rigid and fixed html, e.g:

    {% include 'header.html' %}
    

    and at most maybe entitiy repitition, e.g. table rows:

    {% include 'foo' with {'foo': 'bar'} %}
    

    So you build your layouts with includes, and you extend your base layouts to make sure your site follows the designated design.

提交回复
热议问题