@@ -139,3 +139,69 @@ php vendor/bin/phpunit
139
139
cd Resources/assets
140
140
yarn test
141
141
```
142
+
143
+ ## Want to implement a cache ?
144
+
145
+ Use symfony/cache
146
+
147
+ `````
148
+ composer require symfony/cache
149
+ `````
150
+ And create your twig extension :
151
+
152
+ ```` php
153
+ <?php
154
+
155
+ namespace App\Twig;
156
+
157
+ use Symfony\Component\String\Slugger\AsciiSlugger;
158
+ use Symfony\Contracts\Cache\CacheInterface;
159
+ use Symfony\Contracts\Cache\ItemInterface;
160
+ use Symfony\UX\LazyImage\BlurHash\BlurHashInterface;
161
+ use Twig\Extension\AbstractExtension;
162
+ use Twig\TwigFilter;
163
+ use Twig\TwigFunction;
164
+
165
+ class BlurHashExtension extends AbstractExtension
166
+ {
167
+ public function __construct(private BlurHashInterface $blurHash, private CacheInterface $cache)
168
+ {}
169
+
170
+ public function getFunctions(): array
171
+ {
172
+ return [
173
+ new TwigFunction('data_uri_thumbnail_cached', [$this, 'createDataUriThumbnailCached']),
174
+ ];
175
+ }
176
+
177
+ public function createDataUriThumbnailCached(string $filename, int $width, int $height, int $encodingWidth = 75, int $encodingHeight = 75): string
178
+ {
179
+ $slugger = new AsciiSlugger();
180
+ $cacheKey = $slugger->slug(implode('-', func_get_args()));
181
+
182
+ $value = $this->cache->get($cacheKey, function (ItemInterface $item) use ($filename, $width, $height, $encodingWidth, $encodingHeight) {
183
+ if (!$item->isHit()) {
184
+ $item->set(
185
+ $this->blurHash->createDataUriThumbnail($filename, $width, $height, $encodingWidth, $encodingHeight)
186
+ );
187
+ }
188
+
189
+ return $item->get();
190
+ });
191
+
192
+ return $value;
193
+ }
194
+ }
195
+ ````
196
+
197
+ And now in your images :
198
+
199
+ ```` twig
200
+ <img
201
+ src="{{ data_uri_thumbnail_cached('https://placeimg.com/970/550', 100, 75) }}"
202
+ data-controller="symfony--ux-lazy-image--lazy-image"
203
+ data-hd-src="https://placeimg.com/970/550?q={{ i }}"
204
+ width="970"
205
+ height="550"
206
+ alt="Image-Descrition">
207
+ ````
0 commit comments