df.to_html() shows in flask html source code, but not a browser's interpretation of that code. How to fix?

Viewed 7

I hope it will be easy but I cannot render a Dataframe.to_html() in flask. How to do it? It renders me a code on my webpage but not a table. Screenshot is below. I have a dictionary. Key is df_html and value is a html code from pandas DataFrame:

results = {
"df_html": df.to_html(index=False, classes='table table-stripped', header=True, escape=False) 
}

Then I render it in my route method like this:

return render_template("results.html", results_dict=results)

then in results.html I have this code (jinja, flask):

{% for table in results_dict.df_html %}
 {{ table|safe }}
{% endfor %}

An it outputs to me a html code (source code). How to fix it and make it show a normal html table? Should I add some tags around jinja-flask code? Update: For some reason each symbol is spaced in this html code generated by pandas Image Link: https://tinypic.host/i/DIlab

1 Answers

The problem is your for loop. df.to_html returns a single string, not a list of strings. So, what you're doing there is iterating through that string character by character. Replace that whole thing with:

{{ results_dict.df_html }}
Related