diff --git a/CHANGELOG b/CHANGELOG index d6d4f0897..1747dd9af 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.18.0 (2015-XX-XX) + * added Twig_Environment::createTemplate() to create a template from a string * added a profiler * fixed filesystem loader cache when different file paths are used for the same template diff --git a/lib/Twig/Environment.php b/lib/Twig/Environment.php index 88101f06a..db0e467f8 100644 --- a/lib/Twig/Environment.php +++ b/lib/Twig/Environment.php @@ -346,6 +346,41 @@ class Twig_Environment return $this->loadedTemplates[$cls] = new $cls($this); } + /** + * Creates a template from source. + * + * This method should not be used as a generic way to load templates. + * + * @param string $name The template name + * @param int $index The index if it is an embedded template + * + * @return Twig_Template A template instance representing the given template name + * + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Syntax When an error occurred during compilation + */ + public function createTemplate($template) + { + $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); + + $loader = new Twig_Loader_Chain(array( + new Twig_Loader_Array(array($name => $template)), + $current = $this->getLoader(), + )); + + $this->setLoader($loader); + try { + $template = $this->loadTemplate($name); + } catch (Exception $e) { + $this->setLoader($current); + + throw $e; + } + $this->setLoader($current); + + return $template; + } + /** * Returns true if the template is still fresh. * diff --git a/lib/Twig/Extension/StringLoader.php b/lib/Twig/Extension/StringLoader.php index 5e1a60d0a..4e1a546c2 100644 --- a/lib/Twig/Extension/StringLoader.php +++ b/lib/Twig/Extension/StringLoader.php @@ -43,22 +43,5 @@ class Twig_Extension_StringLoader extends Twig_Extension */ function twig_template_from_string(Twig_Environment $env, $template) { - $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); - - $loader = new Twig_Loader_Chain(array( - new Twig_Loader_Array(array($name => $template)), - $current = $env->getLoader(), - )); - - $env->setLoader($loader); - try { - $template = $env->loadTemplate($name); - } catch (Exception $e) { - $env->setLoader($current); - - throw $e; - } - $env->setLoader($current); - - return $template; + return $env->createTemplate($template); }