diff --git a/src/Template.php b/src/Template.php index ffbaae1ea1c..a45bf6e1e06 100644 --- a/src/Template.php +++ b/src/Template.php @@ -235,12 +235,21 @@ public function renderParentBlock($name, array $context, array $blocks = []) */ public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true) { + $level = ob_get_level(); if ($this->env->isDebug()) { ob_start(); } else { ob_start(function () { return ''; }); } - $this->displayBlock($name, $context, $blocks, $useBlocks); + try { + $this->displayBlock($name, $context, $blocks, $useBlocks); + } catch (\Throwable $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } return ob_get_clean(); } diff --git a/src/TemplateWrapper.php b/src/TemplateWrapper.php index 1ecd82251f3..e94e983ce65 100644 --- a/src/TemplateWrapper.php +++ b/src/TemplateWrapper.php @@ -60,24 +60,7 @@ public function getBlockNames(array $context = []): array public function renderBlock(string $name, array $context = []): string { - $context = $this->env->mergeGlobals($context); - $level = ob_get_level(); - if ($this->env->isDebug()) { - ob_start(); - } else { - ob_start(function () { return ''; }); - } - try { - $this->template->displayBlock($name, $context); - } catch (\Throwable $e) { - while (ob_get_level() > $level) { - ob_end_clean(); - } - - throw $e; - } - - return ob_get_clean(); + return $this->template->renderBlock($name, $this->env->mergeGlobals($context)); } public function displayBlock(string $name, array $context = []) diff --git a/tests/TemplateTest.php b/tests/TemplateTest.php index b14a0384a8f..154f0e8c07a 100644 --- a/tests/TemplateTest.php +++ b/tests/TemplateTest.php @@ -130,13 +130,7 @@ public function testRenderBlockWithUndefinedBlock() $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig, 'index.twig'); - try { - $template->renderBlock('unknown', []); - } catch (\Exception $e) { - ob_end_clean(); - - throw $e; - } + $template->renderBlock('unknown', []); } public function testDisplayBlockWithUndefinedBlock()