Skip to content

Commit

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

* Update ToHtmlTest.php

Add a test to check if the 'styles' attribute works correctly

* Update rendering-media.md

* Update rendering-media.md

* Update ToHtmlTest.php

* Update ToHtmlTest.php

* Update ToHtmlTest.php

* Update ToHtmlTest.php

* Update ToHtmlTest.php

* Update ToHtmlTest.php

* Update ToHtmlTest.php
  • Loading branch information
misaf authored Feb 17, 2024
1 parent 30093e6 commit d94b110
Show file tree
Hide file tree
Showing 3 changed files with 25 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 @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/MediaCollections/HtmlableMedia.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
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 @@ -46,6 +46,17 @@
);
});

it('can render an array of styles as extra attributes', function () {
$this->assertEquals(
'<img style="background-color: blue; color: blue;" src="/media/1/conversions/test-thumb.jpg" alt="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();

Expand Down

0 comments on commit d94b110

Please sign in to comment.