A custom twig extension to add
Add the library to your app's composer.json
:
"require": {
"ed.sukharev/twig-picture-extension": "~1.0",
...
}
Add the extension to the Twig_Environment
:
use PictureExtension\Twig\Extension\Picture;
$twig = new Twig_Environment(...);
$twig->addExtension(new Picture());
The extension provides a picture
twig function, which generates a picture tag with a set of sources and fallback img tag:
{{ picture('/img/path/filename.png', 'My image alt text') }}
Which creates following output:
<picture>
<source srcset="/img/path/filename.webp" type="image/webp">
<source srcset="/img/path/filename.png" type="image/png">
<img src="/img/path/filename.png" alt="My image alt text">
</picture>
The picture
function accepts 3 arguments:
picture($filename, $imgAlt, $imgClasses = [])
- filename: The filename of original image. Picture function substitutes the extension with appropriate when needed.
- alt: This is alternative text to be shown when image not available. Required so that you don't forget to add it.
- imgClasses: Array of strings to be added to
class
attribute of fallbackimg
tag.
# app/config/config.yml
services:
pciture_extension.twig.picture:
class: PictureExtension\Twig\Extension\Picture
tags:
- { name: twig.extension }