【问题标题】:SVG does not display when embedded in HTML. Displays just fine on its own嵌入 HTML 时不显示 SVG。单独显示就好
【发布时间】:2018-04-14 11:17:14
【问题描述】:

我正在使用 Flask 制作一个网络应用程序。我创建了以下函数来动态渲染不同颜色的 SVG 图标。

所有测试均在 Mac OSX 上的最新 Google Chrome 中完成。

@app.route("/testicon")
def testicon():
    return render_template("icons/test.svg", primary="ff0000")

(显然primary参数在实践中没有硬编码,这只是一个演示)

此函数呈现以下 SVG 文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   height="150"
   width="150">
  <path
     id="path3800" class="icon-primary"
     d="m 32.745902,139.71585 -0.385246,-80.002735 31.333333,-41.349727  z"
     style="fill:#{{ primary }};stroke:none;" />
</svg>

(同样,为了演示,这被简化了。)

当我启动 Flask 服务器并访问 localhost:5000/testicon 时,SVG 会完全按照应有的方式显示。但是,我创建了以下函数和随附的模板:

@app.route("/test")
def test():
    return render_template("test.html")

test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<img src="{{ url_for('gameplay.testicon') }}" height="300px" width="300px">

</body>
</html>

访问localhost:5000/test 时,没有任何显示。我可以检查img 元素并发现它的src 属性确实是/testicon,但SVG 不显示。它改为显示标准的“找不到图像”图标。但是,我可以右键单击它并选择“在新选项卡中打开图像”,图像再次显示正常。如果我在图像的src 中放置了错误链接,Google Chrome 控制台不会显示任何错误。

我必须做些什么才能让这张图片正确显示?

【问题讨论】:

    标签: python html svg flask


    【解决方案1】:

    我在点击“提交”之前就找到了答案,所以我想我会把答案放在这里。

    我需要设置响应的 MIME 类型。我将 testicon 函数更改为:

    @app.route("/testicon")
    def testicon():
        response = make_response(render_template("icons/test.svg", primary="ff0000"))
        response.mimetype = "image/svg+xml"
        return response
    

    现在可以完美运行了。

    【讨论】:

      猜你喜欢
      • 2011-12-01
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多