diff --git a/CHANGELOG.md b/CHANGELOG.md index 01bd21b81..8360e6be9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ * Fixed RequestHandlers `NotFoundException` having empty request * Block `.json` files in web server configs * Disabled pretty debug info for Flex as it slows down Twig rendering + * Fixed Twig being very slow when templates do not exist # v1.7.25 ## 11/16/2021 diff --git a/system/src/Grav/Common/Twig/TwigEnvironment.php b/system/src/Grav/Common/Twig/TwigEnvironment.php index bebbdf16e..357e94bce 100644 --- a/system/src/Grav/Common/Twig/TwigEnvironment.php +++ b/system/src/Grav/Common/Twig/TwigEnvironment.php @@ -10,6 +10,9 @@ namespace Grav\Common\Twig; use Twig\Environment; +use Twig\Error\LoaderError; +use Twig\Template; +use Twig\TemplateWrapper; /** * Class TwigEnvironment @@ -18,4 +21,38 @@ use Twig\Environment; class TwigEnvironment extends Environment { use WriteCacheFileTrait; + + /** + * @inheritDoc + */ + public function resolveTemplate($names) + { + if (!\is_array($names)) { + $names = [$names]; + } + + $count = \count($names); + foreach ($names as $name) { + if ($name instanceof Template) { + return $name; + } + if ($name instanceof TemplateWrapper) { + return $name; + } + + if (1 !== $count && !$this->getLoader()->exists($name)) { + continue; + } + + try { + return $this->loadTemplate($name); + } catch (LoaderError $e) { + if (1 === $count) { + throw $e; + } + } + } + + throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); + } }