diff --git a/docs/advanced-usage/rendering-media.md b/docs/advanced-usage/rendering-media.md index 96cee6dcf..4d9813006 100644 --- a/docs/advanced-usage/rendering-media.md +++ b/docs/advanced-usage/rendering-media.md @@ -39,6 +39,16 @@ Here is the image with some classes: {{ $media->img()->attributes(['class' => [ ]]) }} ``` +You may also pass an array of styles to the `style` attribute. This way, you can conditionally add styles where the key is the style name and the value is a boolean indicating whether the style should be added. Elements with a numeric key will always be added. Under the hood, this uses Laravel `Arr::toCssStyles()` [helper method](https://laravel.com/docs/10.x/helpers#method-array-to-css-styles). + +```blade +Here is the image with some styles: {{ $media->img()->attributes(['style' => [ + 'my-style: value', + 'my-other-style: value', + 'my-third-style: value' => true, +]]) }} +``` + If you want [defer loading offscreen images](https://css-tricks.com/native-lazy-loading/) you can use the `lazy` function. ```blade diff --git a/src/MediaCollections/HtmlableMedia.php b/src/MediaCollections/HtmlableMedia.php index a623d9ccb..786363419 100644 --- a/src/MediaCollections/HtmlableMedia.php +++ b/src/MediaCollections/HtmlableMedia.php @@ -28,6 +28,10 @@ public function attributes(array $attributes): self $attributes['class'] = Arr::toCssClasses($attributes['class']); } + if (is_array($attributes['style'] ?? null)) { + $attributes['style'] = Arr::toCssStyles($attributes['style']); + } + $this->extraAttributes = $attributes; return $this; diff --git a/tests/Feature/Media/ToHtmlTest.php b/tests/Feature/Media/ToHtmlTest.php index 279212f26..a0d480ee3 100644 --- a/tests/Feature/Media/ToHtmlTest.php +++ b/tests/Feature/Media/ToHtmlTest.php @@ -46,6 +46,17 @@ ); }); +it('can render an array of styles as extra attributes', function () { + $this->assertEquals( + 'test', + Media::first()->img('thumb', ['style' => [ + 'background-color: blue', + 'color: blue' => true, + 'width: 10px' => false, + ]]), + ); +}); + test('a media instance is htmlable', function () { $media = Media::first();