diff --git a/CHANGELOG.md b/CHANGELOG.md index 19cbb30..5092cc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +## v2.1.1 (2025-06-19) + +### Changed + +- Do not render empty `class` or `style` attribute ([#38](https://github.com/studiometa/twig-toolkit/pull/38), [65e5693](https://github.com/studiometa/twig-toolkit/commit/65e5693)) + ## v2.1.0 (2025-06-17) ### Added diff --git a/src/Helpers/Html.php b/src/Helpers/Html.php index b77d49f..61c8bd3 100644 --- a/src/Helpers/Html.php +++ b/src/Helpers/Html.php @@ -217,6 +217,13 @@ public static function renderAttributes(Environment $env, array $attributes):str continue; } + $value = trim($value); + + // Prevent printing empty style or class attributes + if (($key === 'style' || $key === 'class') && $value === '') { + continue; + } + $renderedAttributes[] = sprintf('%s="%s"', $key, $value); } diff --git a/tests/Helpers/HtmlTest.php b/tests/Helpers/HtmlTest.php index 45ff492..be6418d 100644 --- a/tests/Helpers/HtmlTest.php +++ b/tests/Helpers/HtmlTest.php @@ -1,5 +1,7 @@ loader->setTemplate('index', $tpl); assertMatchesSnapshot(test()->twig->render('index')); }); + + +test('The Html::renderAttributes() method does not print empty class or style attribute', function() { + expect(Html::renderAttributes(test()->twig, ['class' => 'foo', 'style' => '', 'id' => '']))->toBe(' class="foo" id=""'); + expect(Html::renderAttributes(test()->twig, ['class' => ' ', 'id' => '']))->toBe(' id=""'); + expect(Html::renderAttributes(test()->twig, ['class' => '', 'style' => ['display' => 'none'], 'id' => '']))->toBe(' style="display: none;" id=""'); +}); diff --git a/tests/Helpers/UrlTest.php b/tests/Helpers/UrlTest.php index 1bf124a..ea30a37 100644 --- a/tests/Helpers/UrlTest.php +++ b/tests/Helpers/UrlTest.php @@ -16,3 +16,7 @@ test('The `Url` class should not encode URL parameters', function () { expect((string)Url::fromString('http://localhost/?key=value&foo=1/2'))->toBe('http://localhost?key=value&foo=1/2'); }); + +test('The `Url::withQuery` method should replace the current query', function() { + expect((string)Url::fromString('http://localhost/?key=value&foo=1/2')->withQuery('foo=bar'))->toBe('http://localhost?foo=bar'); +});