Skip to content

Commit 7b397b4

Browse files
committed
Filters::renderHtmlAttribute() specially supports bool attributes
1 parent 5037446 commit 7b397b4

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

src/Latte/Helpers.php

+8
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ class Helpers
2222
'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1, 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1,
2323
];
2424

25+
/** @var array<string, int> boolean HTML attributes */
26+
public static array $booleanAttributes = [
27+
'allowfullscreen' => 1, 'async' => 1, 'autofocus' => 1, 'autoplay' => 1, 'checked' => 1, 'controls' => 1, 'default' => 1, 'defer' => 1,
28+
'disabled' => 1, 'formnovalidate' => 1, 'inert' => 1, 'ismap' => 1, 'itemscope' => 1, 'loop' => 1, 'multiple' => 1, 'muted' => 1,
29+
'nomodule' => 1, 'novalidate' => 1, 'open' => 1, 'playsinline' => 1, 'readonly' => 1, 'required' => 1, 'reversed' => 1, 'selected' => 1,
30+
'shadowrootclonable' => 1, 'shadowrootdelegatesfocus' => 1, 'shadowrootserializable' => 1,
31+
];
32+
2533

2634
/**
2735
* Finds the best suggestion.

src/Latte/Runtime/Filters.php

+3
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,9 @@ public static function renderHtmlAttribute(string $name, mixed $value): ?string
288288
} elseif ($value === true) {
289289
return $name;
290290

291+
} elseif (isset(Latte\Helpers::$booleanAttributes[$name])) {
292+
return $value ? $name : null;
293+
291294
} elseif (is_array($value)) {
292295
if (str_starts_with($name, 'data-')) {
293296
return $name . "='"

tests/filters/renderHtmlAttribute.phpt

+2-1
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,10 @@ test('Regular text attributes', function () {
3737

3838
test('boolean attributes', function () {
3939
Assert::same('disabled', Filters::renderHtmlAttribute('disabled', true));
40+
Assert::same('disabled', Filters::renderHtmlAttribute('disabled', 1));
4041
Assert::null(Filters::renderHtmlAttribute('disabled', false));
4142
Assert::null(Filters::renderHtmlAttribute('required', null));
42-
Assert::same('readonly="0"', Filters::renderHtmlAttribute('readonly', 0));
43+
Assert::null(Filters::renderHtmlAttribute('readonly', 0));
4344
});
4445

4546

0 commit comments

Comments
 (0)