'Flask not rendering pandas pd.to_html() as table [duplicate]

Im trying to convert a dataframe to aviable HTML table for flask and Jinja to display on my web browser.

My python code produces my dataframe among other things inside a dictionary such as this:

practice_data = [{
'Author': 'Practice1',
'Title': 'Blog Title',
'Content': 'BTC',
'Date': f'{datetime.datetime.now()}',
'Data': pd.DataFrame(data.data('BTC', 'GBP', datetime.datetime(2020, 5, 1),
                               datetime.datetime(2022, 4, 9)).crypto()).to_html(classes='data',
                                                                                header=True,
                                                                                table_id='table') # data.data is web.DataReader library that returns a dataframe.

And then I have a flask app and route home with this:

app = Flask(__name__)
@app.route('/')
@app.route('/home')
def home():
    return render(
        template_name_or_list='home/home.html',
        **{'content': practice_data})

While my html extends a basic layout like this:

{%extends 'layout.html' %}
{%block content_specific %}
    {%for data in content %}
        <h1>{{data.Title}}</h1>
        <p>By, {{data.Author}} on {{data.Date}}</p>
        <p>{{data.Content}}</p>
        <div class="container">
            {{data.Data}}
        </div>
    {%endfor %}
{%endblock content_specific %}

Now I dont quite get why it wont render the html coming out of pd.to_html() normally, and just shows it like this:

erroneous render

I have looked at other solutions but most start of with dataframe in a variable and not in a dictionary called from a function. So I suspected it has got to do with how I do a for loop in html or access such types of nested functions inside a dictionary.



Solution 1:[1]

The reason it was displaying them as strings is because of how Jinja renders in Flask.

(CORRECT) Simply by adding '| safe' like so:

<div class="container">
            {{data.Data | safe }}
</div>

(INCORRECT) Instead of just:

<div class="container">
            {{data.Data}}
</div>

It works well.

correct display

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Human006