SVG Sprite
App\Util\SvgSpriteUtil combines SVG Twig templates into one hidden <svg> sprite. Each icon is then referenced with <use>, so markup that repeats an icon many times, such as a list of 50 teasers, only contains it once.
Building a sprite
Section titled “Building a sprite”Pass the symbols to SvgSpriteUtil::sprite() as id => source, and add the result to the context:
use App\Util\SvgSpriteUtil;
$context['icon_sprite'] = SvgSpriteUtil::sprite([ 'icon-arrow' => ['template' => 'icons/arrow.twig', 'inherit_fill' => true], 'icon-underline' => ['template' => 'icons/underline.twig', 'stretch' => true],]);| Option | Type | Description |
|---|---|---|
| template | string | Twig template that renders the <svg> |
| inherit_fill | bool | Remove the fill attributes so the icon takes the fill set in CSS. Default false |
| stretch | bool | Set preserveAspectRatio="none" so the icon stretches to its box, e.g. for decorative lines. Default false |
The viewBox and preserveAspectRatio of the source <svg> are kept.
Using it
Section titled “Using it”Output the sprite once, before the icons that use it, then reference a symbol by its id:
{{ icon_sprite|raw }}
<svg class="icon" aria-hidden="true"><use href="#icon-arrow"></use></svg>Size the referencing <svg> in CSS. With inherit_fill, colour it with fill:
.icon { width: rem(16px); height: rem(16px); fill: currentColor;}
