From bf49318decdf9a12c8e7a0083be8375f2b1ded9e Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Sun, 9 Oct 2022 17:04:54 +0200 Subject: [PATCH 1/3] Add "html_attributes" twig filter for easiely write attributes as objects --- HtmlExtension.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/HtmlExtension.php b/HtmlExtension.php index 73a6db5..522d448 100644 --- a/HtmlExtension.php +++ b/HtmlExtension.php @@ -28,6 +28,7 @@ public function getFilters() { return [ new TwigFilter('data_uri', [$this, 'dataUri']), + new TwigFilter('html_attributes', [$this, 'htmlAttributes'], ['is_safe' => ['html']]), ]; } @@ -79,6 +80,26 @@ public function dataUri(string $data, string $mime = null, array $parameters = [ return $repr; } + + /** + * @param array{string, string|bool} $attributes + */ + public function htmlAttributes(array $attributes): string + { + /** @var string[] $htmlAttributes */ + $htmlAttributes = []; + foreach ($attributes as $key => $value) { + if (\is_bool($value) && $value) { + $htmlAttributes[] .= $key; + + continue; + } + + $htmlAttributes[] .= $key . '="' . $value . '"'; + } + + return \implode(' ', $htmlAttributes); + } } } From 3ad63271487d6003275af9abda9b385392d10903 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Mon, 10 Oct 2022 15:30:57 +0200 Subject: [PATCH 2/3] Fix boolean attributes --- HtmlExtension.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/HtmlExtension.php b/HtmlExtension.php index 522d448..a6fb7fb 100644 --- a/HtmlExtension.php +++ b/HtmlExtension.php @@ -89,8 +89,10 @@ public function htmlAttributes(array $attributes): string /** @var string[] $htmlAttributes */ $htmlAttributes = []; foreach ($attributes as $key => $value) { - if (\is_bool($value) && $value) { - $htmlAttributes[] .= $key; + if (\is_bool($value)) { + if ($value) { + $htmlAttributes[] .= $key; + } continue; } From 87248a0e840255405398b17dd37eabe9a850b1e6 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Mon, 10 Oct 2022 15:38:28 +0200 Subject: [PATCH 3/3] Add handling for null value --- HtmlExtension.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/HtmlExtension.php b/HtmlExtension.php index a6fb7fb..742db62 100644 --- a/HtmlExtension.php +++ b/HtmlExtension.php @@ -82,7 +82,7 @@ public function dataUri(string $data, string $mime = null, array $parameters = [ } /** - * @param array{string, string|bool} $attributes + * @param array{string, string|bool|null} $attributes */ public function htmlAttributes(array $attributes): string { @@ -99,6 +99,10 @@ public function htmlAttributes(array $attributes): string $htmlAttributes[] .= $key . '="' . $value . '"'; } + + if ($value === null) { + continue; + } return \implode(' ', $htmlAttributes); }