From 8d1795d4a1a11841f192f4d5bd7465bf2c79c553 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Wed, 13 Sep 2023 16:00:34 +0200 Subject: [PATCH] added function blockExists() [Closes #345] --- src/Latte/Essential/CoreExtension.php | 9 +++++++++ tests/tags/block.blockExists.phpt | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 tests/tags/block.blockExists.phpt diff --git a/src/Latte/Essential/CoreExtension.php b/src/Latte/Essential/CoreExtension.php index 09a490620..3c45fb447 100644 --- a/src/Latte/Essential/CoreExtension.php +++ b/src/Latte/Essential/CoreExtension.php @@ -15,6 +15,7 @@ use Latte\Compiler\Nodes\TextNode; use Latte\Compiler\Tag; use Latte\Compiler\TemplateParser; +use Latte\Runtime; use Latte\RuntimeException; use Nette; @@ -28,6 +29,7 @@ final class CoreExtension extends Latte\Extension private array $functions; private bool $strict; + private Runtime\Template $template; public function beforeCompile(Latte\Engine $engine): void @@ -37,6 +39,12 @@ public function beforeCompile(Latte\Engine $engine): void } + public function beforeRender(Runtime\Template $template): void + { + $this->template = $template; + } + + public function getTags(): array { return [ @@ -180,6 +188,7 @@ public function getFunctions(): array 'last' => [Filters::class, 'last'], 'odd' => [Filters::class, 'odd'], 'slice' => [Filters::class, 'slice'], + 'blockExists' => fn(string $name): bool => $this->template->hasBlock($name), ]; } diff --git a/tests/tags/block.blockExists.phpt b/tests/tags/block.blockExists.phpt new file mode 100644 index 000000000..1c2e40086 --- /dev/null +++ b/tests/tags/block.blockExists.phpt @@ -0,0 +1,23 @@ +setLoader(new Latte\Loaders\StringLoader); + +Assert::match( + <<<'EOD' + Main: true + Foo: false + EOD, + $latte->renderToString(<<<'EOD' + {block main}{/block} + Main: {=var_export(blockExists(main), true)} + Foo: {=var_export(blockExists(foo), true)} + EOD), +);