Reputation: 205
Within my views.py file I have a function that when called via a request, generates an .svg file. I then want this function to render the template and display said .svg file.
Code I have so far (simplified):
views:
def home(request):
# ---------------------------------------
# generate test.svg file and save to a buffer
# ---------------------------------------
svg_data = open("buffer/test.svg", "rb").read()
data = {
'image': svg_data
}
return render(request, 'blog/home.html', data)
template:
{% extends "blog/base.html" %}
{% block content %}
<svg>
{{ image }}
</svg>
{% endblock content %}
Unfortunately when I attempt to access the {{ image }} tag within the template, it displays nothing. So I ask, is there a way that I can load an .svg file in my views function and have it displayed within my template?
Upvotes: 0
Views: 1668
Reputation: 7744
I came across a same problem where when I had passed the svg
as text to the django template, and it simply displayed the text as opposed to rendering it. The error turned out to be due to the svg
text itself being rendered as a string.
If you check your HTML console you should be able to see that the svg
text will be stringified.
The easiest way I solved it is with the safe
filter, e.g.,
{{ svg_data|safe}}
In the case of the OP it should have worked with
{{ image|safe }}
Upvotes: 0
Reputation: 2547
If your SVG image is in a template folder, you can simply use:
<svg>
{% include "buffer/test.svg" %}
</svg>
Or if the location of the file is somewhere other than your template directory, you can create a custom filter tag and use the tag.
@register.simple_tag
def include_anything(file_name):
return open(file_name).read()
and then use {% include_anything '/full/path/to/file.svg' %}
Upvotes: 1