包含擴充套件使用巨集嵌入的比較

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 %}