Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* Add a way to mark a `Twig\Markup` instance as safe for some escaping strategies only
* Make `Environment::getExtension()` return the runtime of an extension class registered with `AttributeExtension`
* Make `Environment::getRuntime()` fall back to the registered extension of the same class
* Speed up `html_attr()` for string values and repeated attribute names

# 3.30.0 (2026-09-25)

Expand Down
15 changes: 13 additions & 2 deletions extra/html-extra/HtmlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,13 +198,24 @@ public static function htmlAttr(Environment $env, iterable|string|false|null ...

$result = '';
$runtime = $env->getRuntime(EscaperRuntime::class);
static $escapedNames = [];
$charset = $env->getCharset();

foreach ($attr as $name => $value) {
if (null === $value = self::htmlAttrValue($name, $value)) {
// a string value is already its own rendering, htmlAttrValue() would return it unchanged
if (!\is_string($value) && null === $value = self::htmlAttrValue($name, $value)) {
continue;
}

$result .= $runtime->escape($name, 'html_attr_relaxed').'="'.$runtime->escape($value).'" ';
if (null === $escapedName = $escapedNames[$charset][$name] ?? null) {
if (\count($escapedNames[$charset] ?? []) >= 1000) {
$escapedNames[$charset] = [];
}

$escapedName = $escapedNames[$charset][$name] = $runtime->escape($name, 'html_attr_relaxed');
}

$result .= $escapedName.'="'.$runtime->escape($value).'" ';
}

return trim($result);
Expand Down
13 changes: 13 additions & 0 deletions extra/html-extra/Tests/HtmlAttrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,19 @@ public static function htmlAttrProvider(): \Generator
],
];

yield 'string values render as themselves whatever the attribute name prefix' => [
'title="a string" style="color: red;" aria-hidden="true" data-json="{"a":1}" data-empty=""',
[
[
'title' => 'a string',
'style' => 'color: red;',
'aria-hidden' => 'true',
'data-json' => '{"a":1}',
'data-empty' => '',
],
],
];

// Boolean attribute handling
yield 'boolean true renders as empty string, except for aria-* and data-* it uses "true"' => [
'required="" aria-disabled="true" data-yes="true"',
Expand Down
Loading