diff --git a/src/Template/Slots.php b/src/Template/Slots.php index e1e6991ddc..77bc148056 100644 --- a/src/Template/Slots.php +++ b/src/Template/Slots.php @@ -2,6 +2,8 @@ namespace Kirby\Template; +use Countable; + /** * The slots collection is simplifying * slot access. Slots can be accessed with @@ -14,7 +16,7 @@ * @copyright Bastian Allgeier * @license https://getkirby.com/license */ -class Slots +class Slots implements Countable { /** * Creates a new slots collection @@ -40,4 +42,12 @@ public function __call(string $name, array $args): Slot|null { return $this->__get($name); } + + /** + * Counts the number of defined slots + */ + public function count(): int + { + return count($this->slots); + } } diff --git a/src/Template/Template.php b/src/Template/Template.php index 3e083a329a..a366ad8850 100644 --- a/src/Template/Template.php +++ b/src/Template/Template.php @@ -163,15 +163,22 @@ public function render(array $data = []): string // take the buffer output from the template as default slot // and render the snippet as final template output if ( - Snippet::$current !== null && - Snippet::$current->parent() === $snippet + Snippet::$current === null || + Snippet::$current->parent() !== $snippet ) { - $template = Snippet::$current->render($data, [ + return $template; + } + + // no slots have been defined, but the template code + // should be used as default slot + if (Snippet::$current->slots()->count() === 0) { + return Snippet::$current->render($data, [ 'default' => $template ]); } - return $template; + // let the snippet close and render natively + return Snippet::$current->render($data); } /** diff --git a/tests/Template/SlotsTest.php b/tests/Template/SlotsTest.php index a4d5c32695..1798c5da0a 100644 --- a/tests/Template/SlotsTest.php +++ b/tests/Template/SlotsTest.php @@ -25,5 +25,6 @@ public function testSlots() $this->assertSame($header, $slots->header()); $this->assertSame($footer, $slots->footer); $this->assertSame($footer, $slots->footer()); + $this->assertCount(2, $slots); } } diff --git a/tests/Template/SnippetTest.php b/tests/Template/SnippetTest.php index 956388399f..d627b31b04 100644 --- a/tests/Template/SnippetTest.php +++ b/tests/Template/SnippetTest.php @@ -223,6 +223,27 @@ public function testRenderWithoutClosing() $this->assertSame("