使用 Twig 声明模板并在父模板块之间传递附加内容

Using Twig to declare template and pass in additional content between the parent template's block

我在布局中多次重复以下代码:

<div id="hi">
    <div class="howAreYou">
        <p class="fineTYForAsking">
            <!-- additional HTML logic goes here -->
        </p>
    </div>
</div>

如何将上面的 html 放入单个 Twig 模板中,然后使用该模板并将我的其他特定 html 放入 <!-- additional HTML logic goes here --> 部分?

您可以只定义块并将模板嵌入任何您想要的地方

partial.twig.html

<div id="{{ id | default('hi') }}">
    <div class="howAreYou">
        <p class="fineTYForAsking">
             {% block content %}
             {% endblock %}
        </p>
    </div>
</div>

template.twig.html

{% embed "partial.html.twig" with { 'id' : 'foo' } %}
    {% block content %}
         Lorem Ipsum
    {% endblock %}
{% endembed %}

您还可以在 for 循环中使用嵌入。循环内已知的变量,在嵌入文件中也是已知的,例如

item.html.twig

<div{% if item.id|default %} id="{{ item.id }}"{% endif %}>
    <div class="howAreYou">
        <p class="fineTYForAsking">
             {% block title %}
                 {% if item.title is defined %}
                 <h1>{{ item.title }}</h1>
                 {% endif %}
             {% endblock %}
             {% block content %}
                 {% if item.content is defined %}
                 <p>{{ item.content }}</p>
                 {% endif %}             
             {% endblock %}            
        </p>
    </div>
</div>

template.html.twig

{% for item in items %}
    {% embed "item.twig" %}
    {% endembed %}
{% endfor %}

demo