Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for passing an array of styles as extra attributes #3542

Merged
merged 12 commits into from
Feb 17, 2024
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