From e0317b1c33331c6e5ff05b80b184bb13ce7b41d3 Mon Sep 17 00:00:00 2001 From: Pascal Baljet Date: Wed, 14 Feb 2024 13:57:24 +0100 Subject: [PATCH] Support for passing an array of classes as extra attributes (#3537) * Support for passing an array of classes as extra attributes * Update rendering-media.md --- docs/advanced-usage/rendering-media.md | 10 ++++++++++ src/MediaCollections/HtmlableMedia.php | 5 +++++ tests/Feature/Media/ToHtmlTest.php | 11 +++++++++++ 3 files changed, 26 insertions(+) diff --git a/docs/advanced-usage/rendering-media.md b/docs/advanced-usage/rendering-media.md index 824a908e4..96cee6dcf 100644 --- a/docs/advanced-usage/rendering-media.md +++ b/docs/advanced-usage/rendering-media.md @@ -29,6 +29,16 @@ You can add extra attributes by calling `attributes`. Here is the image with some attributes: {{ $media->img()->attributes(['class' => 'my-class']) }} ``` +You may also pass an array of classes to the `class` attribute. This way, you can conditionally add classes where the key is the class name and the value is a boolean indicating whether the class should be added. Elements with a numeric key will always be added. Under the hood, this uses Laravel `Arr::toCssClasses()` [helper method](https://laravel.com/docs/10.x/helpers#method-array-to-css-classes). + +```blade +Here is the image with some classes: {{ $media->img()->attributes(['class' => [ + 'my-class', + 'my-other-class' => true, + 'my-third-class' => false, +]]) }} +``` + 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 e6e849854..a623d9ccb 100644 --- a/src/MediaCollections/HtmlableMedia.php +++ b/src/MediaCollections/HtmlableMedia.php @@ -3,6 +3,7 @@ namespace Spatie\MediaLibrary\MediaCollections; use Illuminate\Contracts\Support\Htmlable; +use Illuminate\Support\Arr; use Spatie\MediaLibrary\Conversions\ConversionCollection; use Spatie\MediaLibrary\Conversions\ImageGenerators\Image; use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory; @@ -23,6 +24,10 @@ public function __construct( public function attributes(array $attributes): self { + if (is_array($attributes['class'] ?? null)) { + $attributes['class'] = Arr::toCssClasses($attributes['class']); + } + $this->extraAttributes = $attributes; return $this; diff --git a/tests/Feature/Media/ToHtmlTest.php b/tests/Feature/Media/ToHtmlTest.php index c73a68b44..279212f26 100644 --- a/tests/Feature/Media/ToHtmlTest.php +++ b/tests/Feature/Media/ToHtmlTest.php @@ -35,6 +35,17 @@ ); }); +it('can render an array of classes as extra attributes', function () { + $this->assertEquals( + 'test', + Media::first()->img('thumb', ['class' => [ + 'rounded', + 'border' => true, + 'border-black' => false, + ]]), + ); +}); + test('a media instance is htmlable', function () { $media = Media::first();