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
: 是否沙箱化模板