使用什么而不是Twig_Loader_String

Dav*_*son 16 symfony twig

我看到Twig_Loader_String该类已被弃用,将在Twig 2.0中删除.此外,来源中的评论表明它应该" 永远不会被使用 ".

包含Twig模板的字符串有许多有效用例.

问题是:用什么代替?

Wou*_*r J 28

Twig_Environment#createTemplate应该使用,如问题弃用Twig_Loader_String:

// the loader is not important, you can even just
// use the twig service in Symfony here
$twig = new \Twig_Environment(...);

$template = $twig->createTemplate('Hello {{ name }}!');
echo $template->render(['name' => 'Bob']);
Run Code Online (Sandbox Code Playgroud)

此代码是最简单的方法,并绕过完整的缓存系统.这意味着它没有坏的东西Twig_Loader_String(每次调用时都不会创建新的缓存条目render;它没有引用其他模板的问题等等),但它仍然没有那么快使用Twig_Loader_Array(如@ AlainTiemblo的回答所示)或Twig_Loader_Filesystem.

  • 这实际上不起作用.首先,Twig_Loader_Array :: __ construct()需要一个数组作为唯一参数.其次,在修复之后,render()调用抛出一个Catchable Fatal Error:类__TwigTemplate_dd0d0e2c37a2d0f8b67dcdcd30ecb79029586ee23cd1c76f343d6878b2fdbb35的对象无法转换为字符串错误. (2认同)

Ala*_*blo 10

Twig_Loader_Array装载机采用数组$templateName => $templateContents作为参数,所以有些东西缓存可以使用模板名称来完成.

所以这个实现工作:

$templates = array('hello' => 'Hello, {{ name }}');
$env = new \Twig_Environment(new \Twig_Loader_Array($templates));
echo $env->render('hello', array('name' => 'Bob'));
Run Code Online (Sandbox Code Playgroud)

要么:

$env = new \Twig_Environment(new \Twig_Loader_Array(array()));
$template = $env->createTemplate('Hello, {{ name }}');
echo $template->render(array('name' => 'Bob')); 
Run Code Online (Sandbox Code Playgroud)

为了弄清楚谣言,从第一个Twig版本开始,Twig_Loader_Array在其构造函数中采用了一个数组.Twig_Loader_Array没有数组初始化的所有答案都是错误的.


Ism*_*kin 9

$tplName = uniqid( 'string_template_', true );
$env = clone $this->getTwig();
$env->setCache(false);
$env->setLoader( new \Twig_Loader_Array( [ $tplName => 'Hello, {{ name }}' ] ));
$html = new Response( $env->render( $tplName, [ 'name' => 'Bob' ] ));

echo $html; // Hello, Bob
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用$ twig-> createTemplate(参见@Wouter J的回答) (2认同)

Leb*_*nik 7

试试吧

$template = $this->container->get('twig')->createTemplate('hello {{ name }}');
echo $template->render(array('name' => 'Fabien'));
Run Code Online (Sandbox Code Playgroud)