Twig

灵活、快速且安全的
PHP 模板引擎

a Symfony Product
文档 函数 include
您正在阅读 Twig 3.x 的文档。切换到 Twig 1.x, 2.x 的文档。

问题与反馈

许可

Twig documentation 在新的 BSD 许可下获得许可。

include

include 函数返回模板的渲染内容

1
2
{{ include('template.html.twig') }}
{{ include(some_var) }}

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

如果您正在使用文件系统加载器,则会在其定义的路径中查找模板。

默认情况下,上下文会传递给模板,但您也可以传递其他变量

1
2
{# template.html.twig will have access to the variables from the current context and the additional ones provided #}
{{ include('template.html.twig', {name: 'Fabien'}) }}

您可以通过将 with_context 设置为 false 来禁用对上下文的访问

1
2
{# only the name variable will be accessible #}
{{ include('template.html.twig', {name: 'Fabien'}, with_context = false) }}
1
2
{# no variables will be accessible #}
{{ include('template.html.twig', with_context = false) }}

如果表达式求值为 \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 标志时,如果模板不存在,Twig 将返回一个空字符串

1
{{ include('sidebar.html.twig', ignore_missing = true) }}

您还可以提供一个模板列表,这些模板在包含之前会检查是否存在。将渲染第一个存在的模板

1
{{ include(['page_detailed.html.twig', 'page.html.twig']) }}

如果设置了 ignore_missing,如果所有模板都不存在,它将回退到不渲染任何内容,否则它将抛出一个异常。

当包含由最终用户创建的模板时,您应该考虑对其进行沙箱化

1
{{ include('page.html.twig', sandboxed: true) }}

参数

  • template: 要渲染的模板
  • variables: 要传递给模板的变量
  • with_context: 是否传递当前上下文变量
  • ignore_missing: 是否忽略丢失的模板
  • sandboxed: 是否沙箱化模板