-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
base: 3.x
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,6 +28,14 @@ public function getFilters(): array | |
{ | ||
return [ | ||
new TwigFilter('data_uri', [$this, 'dataUri']), | ||
new TwigFilter( | ||
'html_attributes', | ||
[$this, 'htmlAttributes'], | ||
[ | ||
'is_safe' => ['html'], | ||
'needs_environment' => true, | ||
] | ||
), | ||
]; | ||
} | ||
|
||
|
@@ -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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. wrong type. |
||
*/ | ||
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') . '"'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. keys must be escaped too |
||
} | ||
|
||
return implode(' ', $htmlAttributes); | ||
} | ||
} | ||
} | ||
|
||
|
There was a problem hiding this comment.
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