diff --git a/docs/1-essentials/02-views.md b/docs/1-essentials/02-views.md index ca89e9f51..5030bc734 100644 --- a/docs/1-essentials/02-views.md +++ b/docs/1-essentials/02-views.md @@ -196,6 +196,18 @@ The `:isset` directive can be used to conditionally render the element it is att

{{ $title }}

``` +The `:isset` directive will also detect when you have multiple cases, and will wrap each variable with `isset()` for you. Consider this example: + +```html +

Welcome!

+``` + +If either `isset($foo)` or `isset($bar)` returns `true`, then the condition is met, and the element will be conditionally rendered. + +You can also use `!isset($foo)` for inverse if needed. + +Note: Ensuring that the expression returns `true` or `false` and thus applies the condition correctly is left down to you, the directive will simply wrap each `$var` with `isset()` preserving operators, without performing any logic checks itself. If you make an incompatible string, it will throw an Exception which you'll be able to view in the Debug log or interface, when enabled. + Since `:isset` is a shorthand for `:if="isset()"`, it can be combined with `:elseif` and `:else`: ```html diff --git a/packages/view/src/Elements/PhpIfElement.php b/packages/view/src/Elements/PhpIfElement.php index 1c1472c1d..c43b383fe 100644 --- a/packages/view/src/Elements/PhpIfElement.php +++ b/packages/view/src/Elements/PhpIfElement.php @@ -47,7 +47,7 @@ public function setElse(Element $element): self public function compile(): string { if ($condition = $this->wrappingElement->consumeAttribute(':isset')) { - $condition = sprintf('isset(%s)', $condition); + $condition = preg_replace('/\$\w+/', 'isset($0)', $condition); } else { $condition = $this->wrappingElement->consumeAttribute(':if'); } diff --git a/tests/Integration/View/TempestViewRendererTest.php b/tests/Integration/View/TempestViewRendererTest.php index 134326e4c..a2c76fc35 100644 --- a/tests/Integration/View/TempestViewRendererTest.php +++ b/tests/Integration/View/TempestViewRendererTest.php @@ -106,6 +106,44 @@ public function test_isset_attribute(): void ); } + public function test_isset_attribute_dual_cases(): void + { + $this->assertSame( + '', + $this->view->render(view('
Hello
')), + ); + + $this->assertSame( + '
else
', + $this->view->render(view('
Hello
else
')), + ); + + $this->assertSame( + '
elseif
', + $this->view->render(view('
Hello
elseif
else
')), + ); + + $this->assertSame( + '
else
', + $this->view->render(view('
Hello
elseif
else
')), + ); + + $this->assertSame( + '
Hello
', + $this->view->render(view('
Hello
', foo: true, bar: false)), + ); + + $this->assertSame( + '
Hello
', + $this->view->render(view('
Hello
', foo: false, bar: true)), + ); + + $this->assertSame( + '
Hello
', + $this->view->render(view('
Hello
', foo: true, bar: true)), + ); + } + public function test_if_with_other_expression_attributes(): void { $html = $this->view->render('
Hello
', show: true, data: 'test');