Skip to content

Commit

Permalink
Support for passing an array of classes as extra attributes (#3537)
Browse files Browse the repository at this point in the history
* Support for passing an array of classes as extra attributes

* Update rendering-media.md
  • Loading branch information
pascalbaljet authored Feb 14, 2024
1 parent 5f18aa2 commit e0317b1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/advanced-usage/rendering-media.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions src/MediaCollections/HtmlableMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions tests/Feature/Media/ToHtmlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@
);
});

it('can render an array of classes as extra attributes', function () {
$this->assertEquals(
'<img class="rounded border" src="/media/1/conversions/test-thumb.jpg" alt="test">',
Media::first()->img('thumb', ['class' => [
'rounded',
'border' => true,
'border-black' => false,
]]),
);
});

test('a media instance is htmlable', function () {
$media = Media::first();

Expand Down

0 comments on commit e0317b1

Please sign in to comment.