Skip to content

Commit 9eac15d

Browse files
authored
[12.x] Support Passing Htmlable Instances to Js::from() (#56159)
* Add support for passing `Htmlable` instance to `Js::from()` * Reorder import for styling
1 parent c0955af commit 9eac15d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/Illuminate/Support/Js.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ protected function convertDataToJavaScriptExpression($data, $flags = 0, $depth =
7070
return $data->toHtml();
7171
}
7272

73+
if ($data instanceof Htmlable) {
74+
$data = $data->toHtml();
75+
}
76+
7377
if ($data instanceof UnitEnum) {
7478
$data = enum_value($data);
7579
}

tests/Support/SupportJsTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Illuminate\Tests\Support;
44

55
use Illuminate\Contracts\Support\Arrayable;
6+
use Illuminate\Contracts\Support\Htmlable;
67
use Illuminate\Contracts\Support\Jsonable;
78
use Illuminate\Support\Js;
89
use Illuminate\Tests\Support\Fixtures\IntBackedEnum;
@@ -128,6 +129,19 @@ public function toArray()
128129
);
129130
}
130131

132+
public function testHtmlable()
133+
{
134+
$data = new class implements Htmlable
135+
{
136+
public function toHtml(): string
137+
{
138+
return '<p>Hello, World!</p>';
139+
}
140+
};
141+
142+
$this->assertEquals("'\u003Cp\u003EHello, World!\u003C\/p\u003E'", (string) Js::from($data));
143+
}
144+
131145
public function testBackedEnums()
132146
{
133147
$this->assertSame('2', (string) Js::from(IntBackedEnum::TWO));

0 commit comments

Comments
 (0)