diff --git a/src/Illuminate/View/ComponentAttributeBag.php b/src/Illuminate/View/ComponentAttributeBag.php index 868a97f5aac3..1b5f1692e253 100644 --- a/src/Illuminate/View/ComponentAttributeBag.php +++ b/src/Illuminate/View/ComponentAttributeBag.php @@ -511,11 +511,22 @@ public function __toString() continue; } + // Empty "alt" explicitly marks an image as decorative; empty "value" and "data-*" + // are valid. For everything else we don't want to render the attribute at all. + if (!in_array($key, ['alt', 'value']) && !str_starts_with($key, 'data') && (is_string($value) && trim($value) === '')) { + continue; + } + if ($value === true) { $value = $key === 'x-data' || str_starts_with($key, 'wire:') ? '' : $key; } - $string .= ' '.$key.'="'.str_replace('"', '\\"', trim($value)).'"'; + // Same as above. We want everything but data and value to be trimmed + $value = !str_starts_with($key, 'data') && $key !== 'value' + ? trim($value) + : $value; + + $string .= ' '.$key.'="'.str_replace('"', '\\"', $value).'"'; } return trim($string); diff --git a/tests/View/ViewComponentAttributeBagTest.php b/tests/View/ViewComponentAttributeBagTest.php index 82fbd8687fa1..098a1af2682a 100644 --- a/tests/View/ViewComponentAttributeBagTest.php +++ b/tests/View/ViewComponentAttributeBagTest.php @@ -51,10 +51,15 @@ public function testAttributeRetrieval() 'test-0' => 0, 'test-0-string' => '0', 'test-empty-string' => '', + 'test-whitespace-string' => ' ', + 'data-test-empty-string' => '', + 'data-test-whitespace-string' => ' ', + 'value' => ' ', + 'alt' => '', ]); - $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" test-empty-string=""', (string) $bag); - $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" test-empty-string=""', (string) $bag->merge()); + $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" data-test-empty-string="" data-test-whitespace-string=" " value=" " alt=""', (string) $bag); + $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" data-test-empty-string="" data-test-whitespace-string=" " value=" " alt=""', (string) $bag->merge()); $bag = (new ComponentAttributeBag) ->merge([ @@ -72,9 +77,14 @@ public function testAttributeRetrieval() 'test-0' => 0, 'test-0-string' => '0', 'test-empty-string' => '', + 'test-whitespace-string' => ' ', + 'data-test-empty-string' => '', + 'data-test-whitespace-string' => ' ', + 'value' => ' ', + 'alt' => '', ]); - $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" test-empty-string=""', (string) $bag); + $this->assertSame('test-string="ok" test-true="test-true" test-0="0" test-0-string="0" data-test-empty-string="" data-test-whitespace-string=" " value=" " alt=""', (string) $bag); $bag = (new ComponentAttributeBag) ->merge([