Skip to main content
go-swarm-icons
On this page

Sprite Collector

Explains registering symbols, generating sprite sheets, and clearing state between page renders.

The SpriteCollector type for building shared SVG sprite sheets from registered icon symbols.

Overview

SpriteCollector accumulates SVG icon symbols during a render pass and produces a hidden sprite sheet for injection into page HTML. It is thread-safe and designed for concurrent use across multiple goroutines.

Types

SpriteCollector

Go
type SpriteCollector struct {
// unexported fields
}

Internally stores a sync.RWMutex-protected map of symbol IDs to their body content and viewBox values.

Functions

NewSpriteCollector

Go
func NewSpriteCollector() *SpriteCollector

Returns a ready-to-use collector with an empty symbol map.

Methods

Register

Go
func (sc *SpriteCollector) Register(id, body, viewBox string)

Stores a symbol under id. First write wins: calling Register again with the same id is a no-op.

The id should follow the "i-{prefix}-{name}" convention (e.g., "i-lucide-home").

ID namespacing: internal SVG references in body are automatically suffixed to prevent collisions in the combined sprite sheet. The suffix is derived from the id by stripping the "i-" prefix. Affected patterns:

Pattern Before After (suffix "lucide-star")
id="g" id="g" id="g-lucide-star"
url(#g) url(#g) url(#g-lucide-star)
href="#g" href="#g" href="#g-lucide-star"
xlink:href="#g" xlink:href="#g" xlink:href="#g-lucide-star"

SpriteSheet

Go
func (sc *SpriteCollector) SpriteSheet(pageHTML []byte) []byte

Scans pageHTML for <use href="#i-..."> and <use xlink:href="#i-..."> references. Looks up each referenced ID in the registered symbols. Returns a hidden <svg> element containing one <symbol> per unique matched reference, sorted by ID.

The output markup:

HTML
<svg aria-hidden="true" style="position:absolute;width:0;height:0;overflow:hidden">
<symbol id="i-lucide-home" viewBox="0 0 24 24">...</symbol>
<symbol id="i-lucide-star" viewBox="0 0 24 24">...</symbol>
</svg>

Returns nil if no matching references are found in pageHTML, or if none of the referenced IDs have been registered.

Duplicate references in the page produce only one <symbol>.

Reset

Go
func (sc *SpriteCollector) Reset()

Clears all registered symbols. Use between pages in a static site build to avoid accumulating symbols from previous renders.

Thread safety

SpriteCollector is protected by a sync.RWMutex. Register acquires a write lock. SpriteSheet acquires a read lock. Multiple goroutines can call Register and SpriteSheet concurrently.

See also

Edit this page

Last updated: