用什么代替 Twig_Loader_String

What to use instead of Twig_Loader_String

我看到 Twig_Loader_String class 已被弃用,并将在 Twig 2.0 中删除。此外,来源中的评论表明它应该“永远不要使用”。

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

问题是:用什么代替?

应该使用

Twig_Environment#createTemplate,如issue deprecating 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']);

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

这似乎确实按预期工作:

$tplName = uniqid( 'string_template_', true );
$env = clone $this->getTwig();
$env->setLoader( new \Twig_Loader_Array( [ $tplName => 'Hello, {{ name }}' ] ));
$html = new Response( $env->render( $tplName, [ 'name' => 'Bob' ] ));
$cacheName = $env->getCacheFilename( $tplName );
if( is_file( $cacheName ) )
{
  unlink( $cacheName );
}
echo $html; // Hello, Bob

我在这里找到了提示:http://twig.sensiolabs.org/doc/recipes.html#using-different-template-sources

请注意,如果模板字符串来自数据库或类似的东西,则不希望删除缓存文件。我将此功能用于呈现动态创建且生命周期非常短的模板,通常是在调试和测试时。

$environment = new \Twig_Environment(new \Twig_Loader_Array(array()));
$template = $environment->createTemplate('{{ template }} {{ replacements }}');

echo $template->render([replacements]);

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'));

或:

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

澄清谣言,从第一个 Twig 版本开始,Twig_Loader_Array 在其构造函数中使用数组。所有在没有数组的情况下初始化 Twig_Loader_Array 的答案都是错误的。

$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

最好的是: http://twig.sensiolabs.org/doc/2.x/recipes.html#loading-a-template-from-a-string

以我为例:

public function parse($content, $maxLoops = 3, $context = array())
{
    if (strlen($content) < 1) {
        return null;
    }

    for ($i = 0; $i < $maxLoops; $i++) {
        $template = $this->container->get('twig')->createTemplate($content);
        $result = $template->render( $context );

        if ($result == $content) {
            break;
        } else {
            $content = $result;
        }
    }

    return $content;
}

试一试

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