我遇到了 Django 对象的问题,每当我在模板上显示 svg 文件时,它都不会显示为图像,而是显示为标签。所以我的问题是如何通过模板显示 SVG 图像?
template.html
{% for icon in icons %}
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="100px" height="auto" viewBox="0 0 208.000000 300.000000" preserveAspectRatio="xMidYMid meet">
{{ icon.icons }}
</svg>
{% endfor %}
icon.icons
数据之一:
<g transform="translate(0.000000,300.000000) scale(0.100000,-0.100000)" fill="#161616" stroke="none">
<path class="node" id="node1" d="M1523 2911 c-30 ..."></path>
</g>
<g transform="translate(0.000000,300.000000) scale(0.100000,-0.100000)" fill="#FFFFFF" stroke="none">
</g>
我使用 TextField
来包含此数据。我认为数据是“字符串”,所以我想知道如何在我的网页上将其显示为 SVG?
最佳答案
使用 safe
怎么样?模板过滤器,如下所示:
{{ icon.icons|safe }}
[更新]:我尝试了你的问题,确实是 TextField
用双引号 ( "<g>...</g>"
) 呈现。我试图把它们脱下来,但没有成功。然后我想,为什么不直接使用优秀的 django-ckeditor
包裹。如果是这样,那么您可以像这样声明您的“丰富”模型字段:
from ckeditor.fields import RichTextField
class MyIcon(models.Model):
icon = RichTextField('Text', help_text='Now text will be stored as a rich text field!')
然后,在您的模板中将其呈现如下:
<!-- template.html -->
{% for icon in icons %}
<svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="100px" height="auto" viewBox="0 0 208.000000 300.000000" preserveAspectRatio="xMidYMid meet">
{{ icon.icon|safe }}
</svg>
{% endfor %}
关于python - 如何使用 Django 对象显示 SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42840680/