python - 如何使用 Django 对象显示 SVG?

标签 python django svg

我遇到了 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/

相关文章:

python - 带有 --help arg 的 git 子命令不起作用

python - 'ManyToManyDescriptor' 对象没有属性 'add' ,为什么?

javascript - 内联 SVG 元素不适用于 Div

python - 在 Pandas 中 read_excel 时修剪工作表名称

Python 正则表达式和 @username 的处理

django - Django 中的多连接查询

python - 在 django 中 prepopulated_fields = {"slug": ("title", )} 不显示所有单词

javascript - 将内联 SVG 转换为 Base64 字符串

javascript - 动画自定义矢量形状

python - 如何在matplotlib中对曲线下的区域进行着色