diff --git a/HtmlExtension.php b/HtmlExtension.php index 73a6db5..742db62 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,32 @@ public function dataUri(string $data, string $mime = null, array $parameters = [ return $repr; } + + /** + * @param array{string, string|bool|null} $attributes + */ + public function htmlAttributes(array $attributes): string + { + /** @var string[] $htmlAttributes */ + $htmlAttributes = []; + foreach ($attributes as $key => $value) { + if (\is_bool($value)) { + if ($value) { + $htmlAttributes[] .= $key; + } + + continue; + } + + $htmlAttributes[] .= $key . '="' . $value . '"'; + } + + if ($value === null) { + continue; + } + + return \implode(' ', $htmlAttributes); + } } }