0

I have a flask app using flask-sqlalchemy and flask-table. My table displays just fine but how can I include images in one of the columns? I have tried modifying what gets sent to the table class to be html with an image tag but the result isn't rendered html.

flask-table docs say that you can pass attributes to the table and there are column types for links and buttons but I can't see a way to pass in images or raw html so that it gets rendered.

Is this possible with flask-table or should I create the table manually?

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 %}

Results

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

In response to @grey

@grey Unfortunately it doesn't. I tried also using the safe flask modifier which is supposed to render the value without escaping characters but seems to have no affect.

Here is the html source after trying a few variations or Markup() and safe

<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>
Imp0ster
  • 1
  • 2

1 Answers1

1

Try to wrap your HTML string with flask.Markup(), it will mark the string as safe, so it will rendered as HTML without escape:

from flask import Markup

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

Not tested yet, let me know if it works.

Grey Li
  • 11,664
  • 4
  • 54
  • 64