7

I am trying to use SVG sprites for the icons in a site, like this:

<svg aria-hidden="true" class="icon">
    <use xlink:href="{% static 'images/site-icons.svg#icon-twitter' %}"></use>
</svg>

However this doesn't work because the # gets escaped by Django and so I end up with:

<svg aria-hidden="true" class="icon">
    <use xlink:href="/static/images/site-icons.svg%23icon-twitter"></use>
</svg>

So no icons are rendered. I have isolated that the problem is the escaping, since it works if I paste the contents of site-icons.svg in the template, and do

<svg aria-hidden="true" class="icon">
    <use xlink:href="#icon-twitter"></use>
</svg>

so the problem is in the escaping.

Does anybody know how to avoid this escaping from happening?

Xirux Nefer
  • 830
  • 1
  • 7
  • 19
  • Related: [Is it possible to pass query parameters via Django's {% url %} template tag?](http://stackoverflow.com/q/4591525/1324033) – Sayse Nov 21 '16 at 20:34

1 Answers1

13

You need to move the id after the static tag

{% static 'images/site-icons.svg#icon-twitter' %}

should be

{% static 'images/site-icons.svg' %}#icon-twitter

The reason behind this is that the static tag's job is to find the path to a static file, so all it needs is the file's location, anything extra needs to be added after so that when the template is rendered, it appears as a single (concatenated?) link

Sayse
  • 42,633
  • 14
  • 77
  • 146