Hassan Baig
Hassan Baig

Reputation: 15844

How to correctly include SVG sprite sheets in Django templates

I created an SVG sprite sheet and am now looking at various ways of using it in my Django templates.

The easiest way is:

  1. Add the spritesheet in the templates/ folder (e.g. templates/svg_spritesheet.svg)
  2. Include it in the Django template like so: {% include "svg_spritesheet.svg" %}
  3. Call upon a given svg in the HTML code via: <svg><use xlink:href="#my_svg"></use></svg>

This has worked for me. But this method has operational imperfections.

For example: I normally park my static assets at {{ STATIC_URL }}. That is better for organization purposes. Secondly, I employ webserver level caching for assets in {{ STATIC_URL }}. I do not employ such caching for my /templates folder however.

So naturally, it seems to me that it would be better if I parked my SVG spritesheets at {{ STATIC_URL }}. But once I do that, how do I include it in my Django template?

None of the following methods work:

  1. {% include 'static/svg_spritesheet.svg' %}
  2. {% include '{{ STATIC_URL }}svg_spritesheet.svg' %}
  3. <object type="image/svg+xml" data="{{ STATIC_URL }}svg_spritesheet.svg"></object>
  4. <link type="image/svg+xml" href="{{ STATIC_URL }}svg_spritesheet.svg">

Can an expert give an illustrative example of how to use SVG sprite sheets that are placed at {{ STATIC_URL }}? Thanks in advance (in case warranted, I'm using Django 1.8.19 for the project in question).


Note: in case you miss it - this question deals with SVG sprite sheets, not individual SVGs. A single sprite sheet contains multiple SVG images - which can be selectively called as (and when) required.

Upvotes: 1

Views: 4903

Answers (3)

Lennybee
Lennybee

Reputation: 1

{{ STATIC_URL }} did not work for me, so I amended it to

<svg><use xlink:href="{% static 'svg_spritesheet.svg' %}#my_image"></use></svg>

Upvotes: 0

Hassan Baig
Hassan Baig

Reputation: 15844

The answer was right under my nose.

Simply insert the required location when rendering an SVG from the spritesheet:

{% load static %}
<svg>
  <use 
    href="{% static "svg_spritesheet.svg" %}#my_image"
  >
  </use>
</svg>

This way, you can keep your SVG spritesheets in the static folder - so all/any caching infrastructure fully applies. Happy coding!

Upvotes: 6

John
John

Reputation: 770

I'm not sure I understood your question, but in Django, the correct way to load static files is by using the staic tag.

Below I show a basic example:

template.html

{% load static %}
<img src="{% static "svg_spritesheet.svg" %}" alt="My svg">

In this way, Django is responsible for managing the url and serve the svg, by using the corresponding storage StaticFilesStorage, which is not called if you generate the url manually

Upvotes: 0

Related Questions