0

I am seeing a strange issue when I attempt to write some data to a HTML table, using Flask. When the page loads, it is printing the data into a single long string as below:

<table class="table table-striped table-hover"><tr><th> Task </th><th> duration </th><th> points </th></tr><tr><td>50 Pullups</td><td>15</td><td>0.5000</tr><tr><td>5K Run</td><td>45</td><td>1.0000</tr><tr><td>Abs of Steel</td><td>30</td><td>1.0000</tr><tr><td>Data Science Study</td><td>60</td><td>1.0000</tr><tr><td>Drums</td><td>30</td><td>1.0000</tr><tr><td>Kegel</td><td>10</td><td>1.0000</tr><tr><td>Metta Bhavna</td><td>25</td><td>1.0000</tr><tr><td>Mindfulness</td><td>30</td><td>1.0000</tr><tr><td>Physio</td><td>10</td><td>1.0000</tr><tr><td>Singing</td><td>30</td><td>1.0000</tr><tr><td>Skipping</td><td>15</td><td>0.0000</tr><tr><td>Sprint</td><td>20</td><td>1.0000</tr><tr><td>Typing</td><td>10</td><td>1.0000</tr><tr><td>Yoga</td><td>15</td><td>1.0000</tr></table>

However, obviously it would be great to have it render as a table. Note that when I copy that HTML code into the page source, it renders fine (so no issue with the HTML in and of itself.)

I have set up my environment as below: NB fetch_results is a script querying a mysql db and returning the results in a string format.

import os
from flask import Flask, render_template

@app.route('/')
def table_maker():
    from myfunctions import fetch_results
    table = fetch_results()
    return render_template('home.html', table = table)

The page source contains:

<div class="container">
    {{ table }}
</div>

Help much appreciated.

JohnL_10
  • 549
  • 5
  • 15
  • Can you screenshot your html page ? try `{{ table|safe }}` – Raja Simon Jun 21 '17 at 04:22
  • `{{ table|safe }}` worked like a charm! Thanks. Do you have any guides to where I might have found such a trick in the literature? A cursory search for 'Python Flask Safe HTML' didn't return me anything that alludes to this solution. – JohnL_10 Jun 21 '17 at 04:30

1 Answers1

7

Use {{ table|safe }}.

safe is one of the Jinja2 built in filter you can use that to solve your problem.

The safe filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled.

Ganesh
  • 3,128
  • 2
  • 17
  • 27
Raja Simon
  • 10,126
  • 5
  • 43
  • 74