Extending or including - what is better in Twig?

后端 未结 5 977
执念已碎
执念已碎 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

    Just to add another, hybrid, option into the mix, you might consider embed as well. It lets you leverage the inheritance from extends but also allows multiple reuses like include does.

    Trivial example:

    "partials/titleize.twig":

    {% block title %}Default Title{% endblock %}

    "some-template.twig" will inherit from it using embed:

    {% embed "partials/titleize.twig" %}
        {% block title %}Section 1{% endblock %}
    {% endembed %}
    
    ...
    
    {% embed "partials/titleize.twig" %}
        {% block title %}Section 2{% endblock %}
    {% endembed %}
    

    Renders

    Section 1

    ...

    Section 2

提交回复
热议问题