Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions src/Helpers/Html.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Helpers/HtmlTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

use Studiometa\TwigToolkit\Helpers\Html;

use function Spatie\Snapshots\assertMatchesSnapshot;

beforeEach(function () {
Expand Down Expand Up @@ -199,3 +201,10 @@ class: 'my-component'
test()->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=""');
});
4 changes: 4 additions & 0 deletions tests/Helpers/UrlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Loading