【问题标题】:Is it possible to display images or render html in a flask-table?是否可以在烧瓶表中显示图像或呈现 html?
【发布时间】:2020-10-17 12:01:12
【问题描述】:

我有一个使用 flask-sqlalchemy 和 flask-table 的烧瓶应用程序。我的表格显示得很好,但是如何在其中一列中包含图像?我尝试将发送到表类的内容修改为带有图像标签的 html,但结果未呈现为 html。

flask-table 文档说您可以将属性传递给表,并且有用于链接和按钮的列类型,但我看不到传递图像或原始 html 以使其呈现的方法。

flask-table 可以做到这一点还是我应该手动创建表?

app.py

​​>
class testTable(Table):
    name = Col('Name')
    image = Col('Image')

@app.route("/table")
def table():
    
    # real app pulls items from db but effectively is the same as below
    # first item modified to be html
    items = [Item('bob','<img src="http://example.com/image.png">'),
            Item('alice', 'http://example.com/image2.png')]

    table = testTable(items)

    return render_template('table.html', table=table)

table.html

{% extends 'base.html' %}

{% block content %}

    <h1>Table</h1>
    
{{ table }}

{% endblock %}

结果

------------------------------------------------------
| Name  | Image                                      |
------------------------------------------------------
| bob   | <img src="http://example.com/image.png">   |
| alice | http://example.com/image2.png              |
------------------------------------------------------

回应@grey

​​>

@grey 不幸的是它没有。我还尝试使用 safe flask 修饰符,它应该在不转义字符的情况下呈现值,但似乎没有任何影响。

这是尝试一些变体或Markup()safe 后的html 源代码

<table class="table table-hover">
<thead class="thead-dark"><tr><th>id</th><th>name</th><th>Image</th></tr></thead>
<tbody>
<tr><td>1</td><td>test1</td><td>https://example.com/test1.png</td></tr>
<tr><td>2</td><td>no markup or safe modifier</td><td>&lt;img src=&#34;https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png&#34;&gt;</td></tr>
<tr><td>3</td><td>Using Markup()</td><td>&lt;img src=&#34;https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png&#34;&gt;</td></tr>
<tr><td>4</td><td>Using Markup() and safe modifier</td><td>&lt;img src=&#34;https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png&#34;&gt;</td></tr>
</tbody>
</table>

【问题讨论】:

    标签: python flask web-applications flask-table


    【解决方案1】:

    尝试用flask.Markup()包裹你的HTML字符串,它会将字符串标记为安全的,所以它会呈现为没有转义的HTML:

    from flask import Markup
    
    tems = [Item('bob', Markup('<img src="http://example.com/image.png">')),
                Item('alice', 'http://example.com/image2.png')]
    

    尚未测试,如果有效,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2011-01-20
      相关资源
      最近更新 更多