Skip to content

Commit e0317b1

Browse files
authored
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
1 parent 5f18aa2 commit e0317b1

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

docs/advanced-usage/rendering-media.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ You can add extra attributes by calling `attributes`.
2929
Here is the image with some attributes: {{ $media->img()->attributes(['class' => 'my-class']) }}
3030
```
3131

32+
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).
33+
34+
```blade
35+
Here is the image with some classes: {{ $media->img()->attributes(['class' => [
36+
'my-class',
37+
'my-other-class' => true,
38+
'my-third-class' => false,
39+
]]) }}
40+
```
41+
3242
If you want [defer loading offscreen images](https://css-tricks.com/native-lazy-loading/) you can use the `lazy` function.
3343

3444
```blade

src/MediaCollections/HtmlableMedia.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Spatie\MediaLibrary\MediaCollections;
44

55
use Illuminate\Contracts\Support\Htmlable;
6+
use Illuminate\Support\Arr;
67
use Spatie\MediaLibrary\Conversions\ConversionCollection;
78
use Spatie\MediaLibrary\Conversions\ImageGenerators\Image;
89
use Spatie\MediaLibrary\Conversions\ImageGenerators\ImageGeneratorFactory;
@@ -23,6 +24,10 @@ public function __construct(
2324

2425
public function attributes(array $attributes): self
2526
{
27+
if (is_array($attributes['class'] ?? null)) {
28+
$attributes['class'] = Arr::toCssClasses($attributes['class']);
29+
}
30+
2631
$this->extraAttributes = $attributes;
2732

2833
return $this;

tests/Feature/Media/ToHtmlTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@
3535
);
3636
});
3737

38+
it('can render an array of classes as extra attributes', function () {
39+
$this->assertEquals(
40+
'<img class="rounded border" src="/media/1/conversions/test-thumb.jpg" alt="test">',
41+
Media::first()->img('thumb', ['class' => [
42+
'rounded',
43+
'border' => true,
44+
'border-black' => false,
45+
]]),
46+
);
47+
});
48+
3849
test('a media instance is htmlable', function () {
3950
$media = Media::first();
4051

0 commit comments

Comments
 (0)