包含扩展使用宏嵌入的比较

Twig 中有各种类型的继承和代码重用:

包括

主要目标是代码重用。考虑在 base.html.twig 中使用 header.html.twigfooter.html.twig 作为例子。

header.html.twig

<nav>
   <div>Homepage</div>
   <div>About</div>
</nav>

base.html.twig

{% include 'header.html.twig' %}
<main>{% block main %}{% endblock %}</main>

扩展

主要目标是垂直继承。考虑将 base.html.twig 扩展到 homepage.html.twigabout.html.twig 中作为例子。

base.html.twig

{% include 'header.html.twig' %}
<main>{% block main %}{% endblock %}</main>

homepage.html.twig

{% extends 'base.html.twig' %}

{% block main %}
<p>You are at the homepage</p>
{% endblock %}

about.html.twig

{% extends 'base.html.twig' %}

{% block main %}
<p>You are at the about page</p>
{% endblock %}

使用

主要目标是水平重用。考虑在 single.product.html.twig(扩展 product.layout.html.twig)和 single.service.html.twig(扩展’service.layout.html.page’)页面中使用 sidebar.product.html.twig。 (它就像宏,但对于块)

sidebar.html.twig

<aside>{% block sidebar %}{% endblock %}</aside>

single.product.html.twig

{% extends 'product.layout.html.twig' %}

{% use 'sidebar.html.twig' %}
{% block main %}
<p>You are at the product page for product number 123</p>
{% endblock %}

single.service.html.twig

{% extends 'service.layout.html.twig' %}

{% use 'sidebar.html.twig' %}
{% block main %}
<p>You are at the service page for service number 456</p>
{% endblock %}

主要目标是在具有变量的许多模板上具有可重用的标记。考虑一个获取一些变量并输出一些标记的函数。

form.html.twig

{%宏输入(名称,值,类型)%} <input type =“{{type | default(’text’)}}”name =“{{name}}”value =“{{value | e}} “}}”/> {%endmacro%}

profile.service.html.twig

{% import "forms.html.twig" as forms %}

<div>{{ forms.input('username') }}</div>

主要目标是阻止覆盖。它同时具有 UseInclude 的功能。考虑在 product.table.html.twigservice.table.html.twig 中嵌入 pagination.html.twig

pagination.html.twig

<div>
    <div>{% block first %}{% endblock %}</div>
    {% for i in (min + 1)..(max - 1) %}
        <div>{{ i }}</div>
    {% endfor %}
    <div>{% block last %}{% endblock %}</div>
</div>

product.table.html.twig

{% set min, max = 1, products.itemPerPage %}

{% embed 'pagination.html.twig' %}
    {% block first %}First Product Page{% endblock %}
    {% block last %}Last Product Page{% endblock %}
{% endembed %}

service.table.html.twig

{% set min, max = 1, services.itemPerPage %}

{% embed 'pagination.html.twig' %}
    {% block first %}First Service Page{% endblock %}
    {% block last %}Last Service Page{% endblock %}
{% endembed %}

请注意,嵌入文件(此处为 pagination.html.twig)可以访问当前上下文(minmax 变量)。你还可以将额外的变量传递给嵌入文件:

pagination.html.twig

<p>{{ count }} items</p>
<div>
    <div>{% block first %}{% endblock %}</div>
    {% for i in (min + 1)..(max - 1) %}
        <div>{{ i }}</div>
    {% endfor %}
    <div>{% block last %}{% endblock %}</div>
</div>

product.table.html.twig

{% set min, max = 1, products|length %}

{% embed 'pagination.html.twig' with {'count': products|length } %}
    {% block first %}First Product Page{% endblock %}
    {% block last %}Last Product Page{% endblock %}
{% endembed %}