Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Django from escaping the # symbol

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?

like image 627
Xirux Nefer Avatar asked Nov 21 '16 20:11

Xirux Nefer


People also ask

How do you turn off Django automatic HTML escaping?

For example, you can check if my_textfield contains a script tag. If so, mark the instance as malicious and return an escaped version of my_textfield (the normal Django behavior). Otherwise, use mark_safe to return your HTML code marked as safe. And all of this doesn't need any migrations to the database.

What is auto escaping in Django?

Definition and UsageThe autoescape tag is used to specify if autoescape is on or off. If autoescape is on, which is default, HTML code in variables will be escaped.

What is automatic escaping?

Auto Escape is an optional mode of execution in the Template System developed to provide a better defense against cross-site scripting (XSS) in web applications.

What is safe in Django template?

Django Templates are safe-by-default, which means that expressions are HTML-escaped by default. However, there are cases where expressions are not properly escaped by default: If your template includes JavaScript, then any expression inside the JavaScript should be JavaScript-escaped and not HTML-escaped.


1 Answers

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

like image 196
Sayse Avatar answered Oct 06 '22 01:10

Sayse