使用什么而不是Twig_Loader_String

时间:2015-06-26 20:47:53

标签: symfony twig

我看到Twig_Loader_String类已被弃用,将在Twig 2.0中删除。此外,源中的注释表明它应该“从不使用”。

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

问题是:使用什么?

7 个答案:

答案 0 :(得分:27)

应使用

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那么快。

答案 1 :(得分: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'));

或者:

$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的所有答案都是错误的。

答案 2 :(得分:7)

$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

答案 3 :(得分:6)

试试吧

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

答案 4 :(得分:1)

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

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

答案 5 :(得分:0)

最好的是: 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;
}

答案 6 :(得分:-2)

这实际上似乎按预期工作:

$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

请注意,如果模板字符串来自数据库或类似内容,则不希望删除缓存文件。我使用此功能来渲染动态创建的模板,并且通常在调试和测试时具有非常短的寿命。