From fd55e1c0104436e13fdd700fb5bb67f474618747 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Tue, 12 Mar 2019 09:27:17 +0100 Subject: [PATCH] fixed "embed" support when used from "template_from_string" --- CHANGELOG | 1 + src/Environment.php | 16 ++++++++++++---- src/Template.php | 9 +++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 510a84bab3..7e9ad26144 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ * 1.38.0 (2019-XX-XX) + * fixed "embed" support when used from "template_from_string" * added the possibility to pass a TemplateWrapper to Twig\Environment::load() * improved the performance of the sandbox * added a spaceless filter diff --git a/src/Environment.php b/src/Environment.php index 4a953fa865..968309946f 100644 --- a/src/Environment.php +++ b/src/Environment.php @@ -351,7 +351,7 @@ public function getTemplateClass($name, $index = null) { $key = $this->getLoader()->getCacheKey($name).$this->optionsHash; - return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index); + return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '___'.$index); } /** @@ -443,9 +443,17 @@ public function load($name) */ public function loadTemplate($name, $index = null) { - $cls = $mainCls = $this->getTemplateClass($name); + return $this->loadClass($this->getTemplateClass($name), $name, $index); + } + + /** + * @internal + */ + public function loadClass($cls, $name, $index = null) + { + $mainCls = $cls; if (null !== $index) { - $cls .= '_'.$index; + $cls .= '___'.$index; } if (isset($this->loadedTemplates[$cls])) { @@ -491,7 +499,7 @@ public function loadTemplate($name, $index = null) } if (!class_exists($cls, false)) { - throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache is corrupted.', $name, $index), -1, $source); + throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source); } } diff --git a/src/Template.php b/src/Template.php index 013e926128..8889c024dd 100644 --- a/src/Template.php +++ b/src/Template.php @@ -351,6 +351,15 @@ protected function loadTemplate($template, $templateName = null, $line = null, $ return $template; } + if ($template === $this->getTemplateName()) { + $class = get_class($this); + if (false !== $pos = strrpos($class, '___', -1)) { + $class = substr($class, 0, $pos); + } + + return $this->env->loadClass($class, $template, $index); + } + return $this->env->loadTemplate($template, $index); } catch (Error $e) { if (!$e->getSourceContext()) {