What to use instead of Twig_Loader_String

前端 未结 7 1952
醉梦人生
醉梦人生 2020-12-25 15:29

I see that the Twig_Loader_String class has been deprecated and will be removed in Twig 2.0. Also, the comments in the source indicate that it should \"NEVE

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-25 15:50

    This actually seems to work as expected:

    $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
    

    I found the hints here: http://twig.sensiolabs.org/doc/recipes.html#using-different-template-sources.

    Note that deleting the cache file would not be desirable if the template string came from a database or something similar. I use this functionality for rendering templates that are created dynamically and have very short life spans, usually when debugging and testing.

提交回复
热议问题