Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of Twig_Loader_String

Tags:

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 "NEVER be used".

There are numerous valid use cases for a string containing a Twig template.

The question is: What to use instead?

like image 392
David Patterson Avatar asked Jun 26 '15 20:06

David Patterson


2 Answers

Twig_Environment#createTemplate should be used, as indicated in the 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']); 

This code is the most simple way and bypasses the complete caching system. This means that it doesn't have the bad things of Twig_Loader_String (it doesn't create a new cache entry each time you call render; it doesn't have problems with referencing other templates; etc.), but it still isn't as quick as using Twig_Loader_Array (as shown by @AlainTiemblo's answer) or Twig_Loader_Filesystem.

like image 60
Wouter J Avatar answered Sep 29 '22 03:09

Wouter J


The Twig_Loader_Array loader takes an array of $templateName => $templateContents as argument, so some cache stuff can be done using the template name.

So this implementation works:

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

Or:

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

To make clear the rumor, since the very first Twig version, Twig_Loader_Array takes an array in its constructor. All answers initializing Twig_Loader_Array without array are wrong.

like image 20
Alain Tiemblo Avatar answered Sep 29 '22 03:09

Alain Tiemblo