Skip to content

Commit 014b67f

Browse files
authored
feat(view): support escaped expression attributes (#1222)
1 parent 6bdb652 commit 014b67f

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed

packages/view/src/Attributes/AttributeFactory.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public function make(string $attributeName): Attribute
1616
$attributeName === ':else' => new ElseAttribute(),
1717
$attributeName === ':foreach' => new ForeachAttribute(),
1818
$attributeName === ':forelse' => new ForelseAttribute(),
19+
str_starts_with($attributeName, '::') => new EscapedExpressionAttribute($attributeName),
1920
str_starts_with($attributeName, ':') => new ExpressionAttribute($attributeName),
2021
default => new DataAttribute($attributeName),
2122
};
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace Tempest\View\Attributes;
4+
5+
use Tempest\View\Attribute;
6+
use Tempest\View\Element;
7+
8+
final class EscapedExpressionAttribute implements Attribute
9+
{
10+
public function __construct(
11+
private string $name,
12+
) {}
13+
14+
public function apply(Element $element): ?Element
15+
{
16+
$attributeValue = $element->getAttribute($this->name);
17+
18+
$element
19+
->addRawAttribute(sprintf(':%s="%s"', ltrim($this->name, ':'), $attributeValue))
20+
->unsetAttribute($this->name);
21+
22+
return $element;
23+
}
24+
}

tests/Integration/View/TempestViewRendererTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,4 +702,11 @@ public function test_if_and_foreach_precedence(): void
702702

703703
$this->assertSnippetsMatch('', $html);
704704
}
705+
706+
public function test_escape_expression_attribute(): void
707+
{
708+
$html = $this->render('<div ::escaped="foo">');
709+
710+
$this->assertSnippetsMatch('<div :escaped="foo"></div>', $html);
711+
}
705712
}

tests/Integration/View/ViewComponentTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,4 +888,13 @@ public function test_repeated_local_var_across_view_components(): void
888888
<div thing="c">c</div>
889889
', $html);
890890
}
891+
892+
public function test_escape_expression_attribute_in_view_components(): void
893+
{
894+
$this->registerViewComponent('x-test', '<div class="foo" ::escaped="foo"></div>');
895+
896+
$html = $this->render('<x-test/>');
897+
898+
$this->assertSnippetsMatch('<div class="foo" :escaped="foo"></div>', $html);
899+
}
891900
}

0 commit comments

Comments
 (0)