include
include
语句包含一个模板,并输出该文件的渲染内容
1 2 3
{% include 'header.html.twig' %}
Body
{% include 'footer.html.twig' %}
注意
建议使用 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.twig' %} {% endset %} {# vs #} {% set content = include('template.html.twig') %} {# Apply filter on a rendered template #} {% apply upper %} {% include 'template.html.twig' %} {% endapply %} {# vs #} {{ include('template.html.twig')|upper }}
- 由于命名参数,
include
函数不对参数的顺序施加任何特定要求。
包含的模板可以访问活动上下文的变量。
如果您正在使用文件系统加载器,则将在其定义的路径中查找模板。
您可以通过在 with
关键字后传递变量来添加额外的变量
1 2 3 4 5
{# template.html.twig will have access to the variables from the current context and the additional ones provided #}
{% include 'template.html.twig' with {'name': 'Fabien'} %}
{% set vars = {'name': 'Fabien'} %}
{% include 'template.html.twig' with vars %}
您可以通过附加 only
关键字来禁用对上下文的访问
1 2
{# only the name variable will be accessible #}
{% include 'template.html.twig' with {'name': 'Fabien'} only %}
1 2
{# no variables will be accessible #}
{% include 'template.html.twig' only %}
提示
当包含由最终用户创建的模板时,您应该考虑对其进行沙盒化处理。更多信息请参见 Twig 沙盒 章节。
模板名称可以是任何有效的 Twig 表达式
1 2
{% include some_var %}
{% include ajax ? 'ajax.html.twig' : 'not_ajax.html.twig' %}
如果表达式求值为 \Twig\Template
或 \Twig\TemplateWrapper
实例,Twig 将直接使用它
1 2 3 4 5
// {% include template %}
$template = $twig->load('some_template.html.twig');
$twig->display('template.html.twig', ['template' => $template]);
您可以使用 ignore missing
标记 include,在这种情况下,如果要包含的模板不存在,Twig 将忽略该语句。它必须放在模板名称之后。以下是一些有效的示例
1 2 3
{% include 'sidebar.html.twig' ignore missing %}
{% include 'sidebar.html.twig' ignore missing with {'name': 'Fabien'} %}
{% include 'sidebar.html.twig' ignore missing only %}
您还可以提供一个模板列表,在包含之前会检查这些模板是否存在。将包含第一个存在的模板
1
{% include ['page_detailed.html.twig', 'page.html.twig'] %}
如果给定了 ignore missing
,如果所有模板都不存在,它将回退到不渲染任何内容,否则将抛出异常。