added Twig_Environment::createTemplate()

This commit is contained in:
Fabien Potencier
2013-11-01 08:45:56 +01:00
parent 675ae52a2a
commit 6ec928e2aa
3 changed files with 37 additions and 18 deletions
+1
View File
@@ -1,5 +1,6 @@
* 1.18.0 (2015-XX-XX) * 1.18.0 (2015-XX-XX)
* added Twig_Environment::createTemplate() to create a template from a string
* added a profiler * added a profiler
* fixed filesystem loader cache when different file paths are used for the same template * fixed filesystem loader cache when different file paths are used for the same template
+35
View File
@@ -346,6 +346,41 @@ class Twig_Environment
return $this->loadedTemplates[$cls] = new $cls($this); 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. * Returns true if the template is still fresh.
* *
+1 -18
View File
@@ -43,22 +43,5 @@ class Twig_Extension_StringLoader extends Twig_Extension
*/ */
function twig_template_from_string(Twig_Environment $env, $template) function twig_template_from_string(Twig_Environment $env, $template)
{ {
$name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); return $env->createTemplate($template);
$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;
} }