From 063f450c7969b5615da66b01a57dd266022da612 Mon Sep 17 00:00:00 2001 From: Eugene Leonovich Date: Tue, 2 Apr 2024 02:06:53 +0200 Subject: [PATCH] Fix overridden blocks are not rendered See https://github.com/rybakit/twig-deferred-extension/issues/17. --- src/DeferredExtension.php | 7 ++++++- tests/Fixtures/first_deferred.test | 12 ++++++++++++ tests/IntegrationTest.php | 6 +----- 3 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 tests/Fixtures/first_deferred.test diff --git a/src/DeferredExtension.php b/src/DeferredExtension.php index aa70449..36cb1eb 100644 --- a/src/DeferredExtension.php +++ b/src/DeferredExtension.php @@ -19,6 +19,7 @@ final class DeferredExtension extends AbstractExtension { private $blocks = []; + private $clearBlocksOnBufferCleanup = true; public function getTokenParsers() : array { @@ -37,7 +38,9 @@ public function defer(Template $template, string $blockName) : void $index = \count($this->blocks[$templateName]) - 1; \ob_start(function (string $buffer) use ($index, $templateName) { - unset($this->blocks[$templateName][$index]); + if ($this->clearBlocksOnBufferCleanup) { + unset($this->blocks[$templateName][$index]); + } return $buffer; }); @@ -51,7 +54,9 @@ public function resolve(Template $template, array $context, array $blocks) : voi } while ($blockName = \array_pop($this->blocks[$templateName])) { + $this->clearBlocksOnBufferCleanup = false; $buffer = \ob_get_clean(); + $this->clearBlocksOnBufferCleanup = true; $blocks[$blockName] = [$template, 'block_'.$blockName.'_deferred']; $template->displayBlock($blockName, $context, $blocks); diff --git a/tests/Fixtures/first_deferred.test b/tests/Fixtures/first_deferred.test new file mode 100644 index 0000000..efcbd72 --- /dev/null +++ b/tests/Fixtures/first_deferred.test @@ -0,0 +1,12 @@ +--TEST-- +first deferred +--TEMPLATE-- +{% extends "layout.twig" %} +{% block bar deferred %}[bar-overridden]{% endblock %} +--TEMPLATE(layout.twig)-- +{% block foo deferred %}[foo]{% endblock %} +{% block bar deferred %}[bar]{% endblock %} +--DATA-- +return [] +--EXPECT-- +[bar-overridden][foo] diff --git a/tests/IntegrationTest.php b/tests/IntegrationTest.php index b05ba37..2d26dc4 100644 --- a/tests/IntegrationTest.php +++ b/tests/IntegrationTest.php @@ -56,11 +56,7 @@ public function testDeferredBlocksAreClearedOnRenderingError() : void ', ]); - $twig = new Environment($loader, [ - 'cache' => false, - 'strict_variables' => true, - ]); - + $twig = new Environment($loader); $twig->addExtension(new DeferredExtension()); $twig->addFunction(new TwigFunction('error', static function () { throw new \RuntimeException('Oops');