template_from_string
template_from_string
函数从字符串加载模板
1 2
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string(page.template)) }}
为了方便调试,您还可以为模板指定一个名称,该名称将成为任何相关错误消息的一部分
1
{{ include(template_from_string(page.template, "template for page " ~ page.name)) }}
注意
template_from_string
函数默认情况下不可用。
在 Symfony 项目中,您需要在您的 services.yaml
文件中加载它
1 2
services:
Twig\Extension\StringLoaderExtension:
或 services.php
文件
1
$services->set(\Twig\Extension\StringLoaderExtension::class);
否则,在 Twig 环境中显式添加扩展
1 2 3 4
use Twig\Extension\StringLoaderExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new StringLoaderExtension());
注意
即使您可能总是将 template_from_string
函数与 include
函数一起使用,您也可以将其与任何将模板作为参数的标签或函数一起使用(例如 embed
或 extends
标签)。
参数
template
:模板name
:模板的名称