Skip to content

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.

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],
]);
OptionTypeDescription
templatestringTwig template that renders the <svg>
inherit_fillboolRemove the fill attributes so the icon takes the fill set in CSS. Default false
stretchboolSet 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.

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;
}