Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "html_attributes" twig filter for easiely write attributes as objects #3760

Draft
wants to merge 3 commits into
base: 3.x
Choose a base branch
from
Draft
Changes from 2 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
37 changes: 37 additions & 0 deletions extra/html-extra/HtmlExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ public function getFilters(): array
{
return [
new TwigFilter('data_uri', [$this, 'dataUri']),
new TwigFilter(
'html_attributes',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this looks more like a function than a filter to me

[$this, 'htmlAttributes'],
[
'is_safe' => ['html'],
'needs_environment' => true,
]
),
];
}

Expand Down Expand Up @@ -79,6 +87,35 @@ public function dataUri(string $data, string $mime = null, array $parameters = [

return $repr;
}

/**
* @param array{string, string|bool|int|float|null} $attributes
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wrong type. array{string, string|bool|int|float|null} means an array with 2 elements, with index 0 being a string and index 1 being string|bool|int|float|null. Instead, you should use array<string, string|bool|int|float|null>

*/
public function htmlAttributes(Environment $environment, array $attributes): string
{
/** @var string[] $htmlAttributes */
$htmlAttributes = [];
foreach ($attributes as $key => $value) {
if (\is_bool($value)) {
// false should never be outputted e.g. disabled, readonly
// this matches also the behaviour here: https://github.com/symfony/symfony/blob/v5.4.14/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig#L465-L476
if ($value) {
$htmlAttributes[] = $key;
}

continue;
}

// null represent no value and should not be outputted for a better DX
if (null === $value) {
continue;
}

$htmlAttributes[] = $key . '="' . twig_escape_filter($environment, $value, 'html_attr') . '"';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

keys must be escaped too

}

return implode(' ', $htmlAttributes);
}
}
}

Expand Down