Twig included template extending parent's block once

后端 未结 2 1935
遇见更好的自我
遇见更好的自我 2021-02-13 11:36

Is there a way to do this? I have a template which outputs one blog article.

Now, on index page I show 10 articles by including that template in

相关标签:
2条回答
  • 2021-02-13 12:00

    You can use a new block (not tested):

    {# index.html.twig #}
    {% block stylesheets -%}
        {% block article_styles '' %}
    {%- endblock %}
    
    {% for ... -%}
        {% include VendorBundle:template.html.twig with {'article': article} %}
    {%- endfor %}
    

    {# template.html.twig #}
    {% block article_styles -%}
        {{ parent() }}
        <link rel=stylesheet href=...>
    {%- endblock %}
    
    {# ... #}
    

    Edit: Added {{ parent() }}, this will print every content the block already has.

    0 讨论(0)
  • 2021-02-13 12:23

    Did you try to use use? Unfortunately I'm not completely sure if I got the question right but {% use %}wasn't mentioned here.

    As I understand the question you've got your article.html.twig and include it in e.g. index.html.twig. Now you want to add something from article.html.twig into index.html.twig? Namely to the {% stylesheets %} block.

    If I got how to use {% use %} you could maybe try it like this.

    article.html.twig

    {% block stylesheets %}
        <link rel="stylesheet" href="{{ asset('bundles/mybundle/css/article.css') }}" type="text/css" />
    {% endblock %}
    {% block article %}
        {# whatever you do here #}
    {% endblock %}
    

    index.html.twig

    {% use "VendorBundle:article.html.twig" with stylesheets as article_styles %}
    {% block stylesheets %}
        {{ block('article_styles') }}
        {# other styles here #}
    {% endblock %}
    {% for article in articles %}
            {% include VendorBundle:article.html.twig with { 'article': article } %}
    {% endfor %}
    

    I have not the chance to test it but the docu states a few very interesting things and it seems like this could be the way to do it.

    Horizontal reuse is an advanced Twig feature that is hardly ever needed in regular templates. It is mainly used by projects that need to make template blocks reusable without using inheritance.

    I am rather new to stackoverflow. So please if my answer is completely useless could you just post a comment before down voting and I delete it? However if it does help and there are just some errors in my example, also inform me and I'll fix it.

    0 讨论(0)
提交回复
热议问题