include

这个 include 函数返回模板的呈现内容:

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

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

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

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

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

您可以通过设置 with_contextfalse

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

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

// {{ include(template) }}

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

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

当你设置 ignore_missing 如果模板不存在,Twig将返回空字符串:

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

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

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

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

包含最终用户创建的模板时,应考虑对其进行沙箱处理:

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

争论

  • template :要呈现的模板
  • variables :要传递给模板的变量
  • with_context :是否传递当前上下文变量
  • ignore_missing :是否忽略丢失的模板
  • sandboxed :是否对模板进行沙盒