TWIG - 如何覆盖嵌入内部的块,但在子模板中?

时间:2015-03-24 14:00:11

标签: symfony twig

所以,我有3个模板:1。使用一些参数嵌入Widget,2。每页的全局布局,3。单页。

我想在Layout中使用Page来覆盖它,但是当我想将这个块放在Embed小部件中时,它就不起作用了。

file: Widget/awesome.html.twig(嵌入小部件)

<div id="{{id|default('awesomeWidget')}}">
    {% block widget_body %}
    {% endblock %}
</div>

file: Layout/layout.html.twig

{% block layout_body %}
    {% embed 'AcmeFoobarBundle:Widget:awesome.html.twig' with 
            {'id':'myAwesomeWidget'} only %}
        {% block widget_body %}
            {% block I_WANT_TO_OVERRIDE_THIS %}
            {% endblock %}
        {% endblock %}
    {% endembed %}
{% endblock %}

file: Portal/page.html.twig

{% extends 'AcmeFoobarBundle:Layout:layout.html.twig' %}

{% block I_WANT_TO_OVERRIDE_THIS %}
    Hello World
{% endblock %}

这有可能以某种方式实现这个想法吗?

2 个答案:

答案 0 :(得分:16)

你不能这样做。嵌入式工作包括include和extends,因此块I_WANT_TO_OVERRIDE_THIS实际上在你的'扩展'awesome.html.twig'中。页面正在扩展layout.html.twig而不是很棒,所以page.html没有I_WANT_TO_OVERRIDE_THIS块

您应该考虑将其更改为您的窗口小部件的占位符,并将它们嵌入到page.html.twig级别。

如果你真的需要这种方式,你最终可以这样做: 在layout.html.twig中:

{% set overrideWidgetPart %}
   {% block I_WANT_TO_OVERRIDE_THIS %}{% endblock %}
{% endset %}

{% block layout_body %}
    {% embed 'AcmeFoobarBundle:Widget:awesome.html.twig' with 
            {'id':'myAwesomeWidget', overrideWidgetPart: overrideWidgetPart } only %}
        {% block widget_body %}
            {{ overrideWidgetPart  }}
        {% endblock %}
    {% endembed %}
{% endblock %}

答案 1 :(得分:2)

接受的答案帮助我弄清楚了一个类似的情况,我在embed中使用嵌入,我希望能够在子嵌入块中注入html。

如果你查看users.html,你会看到我使用{% set footer %}{% endset %},它允许我将html传递给子嵌入{% block footer %}块。

users.html

{% embed 'user_widget.twig'
    with { user: user } only %}        
    {% set footer %}
        <div class='footer'>content here</div>
    {% endset %}
{% endembed %}

user_widget.twig

{% embed 'user_widget.tpl' with {
    open: true,
    id: user.uid
}%}
    <div class='user_header'>{{ user.name }}</div>    
    {% block content %}
        {% embed "user_info.twig" with {
            id: user.id,
            photo: user.picture,
            footer_html: footer} only %}
                {% block footer %}{{ footer_html }}{% endblock %}
        {% endembed %}
    {% endblock %}
{% endembed %}

user_info.twig

<div class='user_info' id='{{ id }}'>
    <img class='user_photo' src='{{ photo }}'>    
    {% block footer %}{% endblock %}
</div>