Reputation: 15844
I created an SVG sprite sheet and am now looking at various ways of using it in my Django templates.
The easiest way is:
templates/
folder (e.g. templates/svg_spritesheet.svg
){% include "svg_spritesheet.svg" %}
<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:
{% include 'static/svg_spritesheet.svg' %}
{% include '{{ STATIC_URL }}svg_spritesheet.svg' %}
<object type="image/svg+xml" data="{{ STATIC_URL }}svg_spritesheet.svg"></object>
<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
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
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
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