21 lines (21 loc) · 1.19 KB
 1{{- /*
 2  Builds a single external SVG sprite from every assets/images/*.svg file and
 3  returns its (fingerprinted) URL. Each icon becomes a <symbol id="name">.
 4  Referenced via <use href="sprite#name"> in partials/svg.html, so the icon
 5  markup leaves the page HTML and the sprite is fetched once and cached.
 6  Call through partialCached so it is built only once per site build.
 7*/ -}}
 8{{- $symbols := slice -}}
 9{{- range (resources.Match "images/*.svg") -}}
10  {{- $name := strings.TrimSuffix ".svg" (path.Base .Name) -}}
11  {{- $c := .Content -}}
12  {{- /* drop XML declaration and leading comments */ -}}
13  {{- $c = replaceRE `(?s)^\s*(?:<\?xml[^>]*>)?\s*(?:<!--.*?-->\s*)*` "" $c -}}
14  {{- $vb := "" -}}
15  {{- with (findRE `viewBox="[^"]*"` $c 1) -}}{{- $vb = index . 0 -}}{{- end -}}
16  {{- $inner := replaceRE `(?s)^.*?<svg[^>]*>(.*)</svg>\s*$` "$1" $c -}}
17  {{- $symbols = $symbols | append (printf `<symbol id="%s" %s>%s</symbol>` $name $vb $inner) -}}
18{{- end -}}
19{{- $svg := printf `<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">%s</svg>` (delimit $symbols "") -}}
20{{- $res := resources.FromString "icons.svg" $svg | minify | fingerprint -}}
21{{- return $res.RelPermalink -}}