Skip to content

Commit

Permalink
added Twig_Environment::createTemplate()
Browse files Browse the repository at this point in the history
  • Loading branch information
fabpot committed Jan 20, 2015
1 parent 675ae52 commit 6ec928e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 18 deletions.
1 change: 1 addition & 0 deletions 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

Expand Down
35 changes: 35 additions & 0 deletions lib/Twig/Environment.php
Expand Up @@ -346,6 +346,41 @@ public function loadTemplate($name, $index = null)
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.
*
Expand Down
19 changes: 1 addition & 18 deletions lib/Twig/Extension/StringLoader.php
Expand Up @@ -43,22 +43,5 @@ public function getName()
*/
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);
}

0 comments on commit 6ec928e

Please sign in to comment.