如何在Python Flask网页中加载SVG文件?

3

我想把一个svg文件作为xml元素嵌入到我的页面中(不是作为图像),我需要这样做才能在页面内动态更改元素。

我写了一段简单的代码,希望它能实现:

@app.route('/map_test/')
def test():
   svg = render_template('file.svg')
   response = make_response(svg)
   response.content_type = 'image/svg+xml'
   return render_template('test.html', svg=response)

和 test.html:

{% block content %}
<section>
    {{ svg }}
</section>
{% endblock %}

...返回了<Response 126181 bytes [200 OK]>而不是svg元素...

那么...我需要做什么才能让它正常工作呢?


你的导入是什么? - Nihal
从flask导入make_response、render_template和request。 - MrSolid51
2个回答

3
这个很管用:
from flask import Markup

@app.route('/map_test/')
def test():
   svg = open('file.svg').read
   return render_template('test.html', svg=Markup(svg))

2
Markup( )?你导入了这个函数吗?它是自定义函数还是内置函数?请编辑你的答案。谢谢。 - Enrique Bruzual
我猜你需要调用read函数。所以svg = open('file.svg').read() - Arpad Horvath -- Слава Україні
无法工作,请参见 https://poketyrunts.repl.co/favicon.svg 和 https://replit.com/@poketyrunts/poketyrunts?v=1 的演示(我希望它像真正的SVG一样)。 - RixTheTyrunt

-2
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
   img = './static/download.svg'

   return render_template('index.html', img=img)


if __name__ == '__main__':
   app.run()

index.html

<!DOCTYPE html>
<html lang="en">
<body>
<img src="{{ img }}">
</body>
</html>

将您的SVG文件放入名为“static”的目录中


2
嗯...我希望我的SVG元素是动态的,所以我一直在尝试加载完整的SVG元素...这将使我将SVG文件作为图片加载,但不允许我动态更改元素。 - MrSolid51

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接