include

这个 include 语句包含一个模板并输出该文件的呈现内容:

1
2
3
{% include 'header.html' %}
    Body
{% include 'footer.html' %}

注解

建议使用 include 功能,因为它提供了相同的功能,具有更大的灵活性:

  • 这个 include 函数在语义上更“正确”(包括在当前范围内输出其呈现内容的模板;标记不应显示任何内容);

  • 这个 include 功能更加“可组合”:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    {# Store a rendered template in a variable #}
    {% set content %}
        {% include 'template.html' %}
    {% endset %}
    {# vs #}
    {% set content = include('template.html') %}
    
    {# Apply filter on a rendered template #}
    {% apply upper %}
        {% include 'template.html' %}
    {% endapply %}
    {# vs #}
    {{ include('template.html')|upper }}
    
  • 这个 include 由于 named arguments .

包含的模板可以访问活动上下文的变量。

如果您使用的是文件系统加载器,那么将在它定义的路径中查找模板。

您可以通过在 with 关键字:

1
2
3
4
5
{# template.html will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html' with {'foo': 'bar'} %}

{% set vars = {'foo': 'bar'} %}
{% include 'template.html' with vars %}

您可以通过附加 only 关键字:

1
2
{# only the foo variable will be accessible #}
{% include 'template.html' with {'foo': 'bar'} only %}
1
2
{# no variables will be accessible #}
{% include 'template.html' only %}

小技巧

当包含由最终用户创建的模板时,您应该考虑对其进行沙箱处理。更多信息请访问 Twig for Developers 章节和 sandbox 标签文档。

模板名称可以是任何有效的Twig表达式:

1
2
{% include some_var %}
{% include ajax ? 'ajax.html' : 'not_ajax.html' %}

如果表达式的计算结果是 \Twig\Template 或A \Twig\TemplateWrapper 例如,Twig将直接使用它:

// {% include template %}

$template = $twig->load('some_template.twig');

$twig->display('template.twig', ['template' => $template]);

可以用标记include ignore missing 在这种情况下,如果要包含的模板不存在,Twig将忽略该语句。它必须放在模板名称之后。以下是一些有效的例子:

1
2
3
{% include 'sidebar.html' ignore missing %}
{% include 'sidebar.html' ignore missing with {'foo': 'bar'} %}
{% include 'sidebar.html' ignore missing only %}

检查模板是否存在,然后提供一个包含列表。存在的第一个模板将包括:

1
{% include ['page_detailed.html', 'page.html'] %}

如果 ignore missing 如果没有模板存在,则返回到不呈现任何内容,否则将引发异常。