Template tags

svg_sprite

The {% svg_sprite %} template tag inserts an SVG tag that uses the specified sprite.

Example

Template:

{% load svg_Sprite %}
{% svg_sprite 'circle' class='icon' fill='crimson' %}

Output:

<svg class="icon" fill="crimson"><use href="/static/sprite.svg#circle"/></svg>

The tag can be used with one or more arguments.

  • The first argument is the id of the SVG sprite.
  • If a title argument is given, a title element will be added to the SVG element.
  • All other arguments are added as attributes to the SVG tag.

Sprite URL

The URL of the sprite (the value of the href attribute of the <use> element) is generated based on STATIC_URL and SVG_SPRITE settings, with the sprite id (see above) added as fragment identifier.

Note

For security reasons, browsers block cross-origin URLs in the href attribute1, so if you serve your static files from another domain, this template tag will not work out of the box.

Default attributes

Attributes from the SVG_SPRITE_DEFAULT_ATTRIBUTES setting are automatically added to all SVG sprites in addition to the attributes specified in a specific template tag:

Example

Settings:

SVG_SPRITE_DEFAULT_ATTRIBUTES = {
    'class': 'icon',
}

Template:

{% svg_sprite 'circle' %} 

Output:

<svg class="icon"><use href="/static/sprite.svg#circle"/></svg>

Attributes specified in the template replace attributes from the defaults of the same name:

Example

Settings:

SVG_SPRITE_DEFAULT_ATTRIBUTES = {
    'class': 'foo bar',
}

Template:

{% svg_sprite 'circle' class='baz' %} 

Output:

<svg class="baz"><use href="/static/sprite.svg#circle"/></svg>

Default attributes can be removed by setting them to None:

Example

Settings:

SVG_SPRITE_DEFAULT_ATTRIBUTES = {
    'class': 'icon',
}

Template:

{% svg_sprite 'circle' class=None %} 

Output:

<svg><use href="/static/sprite.svg#circle"/></svg>

  1. See MDN