Prakash
Prakash

Reputation: 119

Flask : render_template handling dataframe as html

I am using the following code to render the dataframe values as HTML and which gets directed to a HTML and it works fine.

@app.route('/index/')
def index():
    return render_template('index.html',tables=[df.head().to_html(classes='table table-striped') ] ,titles=df.columns.values )

i do have another dataframe which needs to be used in the same 'index.html'.I tried adding the same in the above code like the below

 @app.route('/index/')
 def index():
     return render_template('index.html',tables=[df.head().to_html(classes='table table-striped'),**dfrme.head().to_html(classes='table1')** ] ,titles=df.columns.values )

It brings up the table one above the other. since i want the other dataframe value to be called in a different area of the index.html need your help for accomplishing the same.

code where it gets rendered:

<table class="w3-table w3-striped w3-border">
  <tr>
    {% for table in tables %}
      {{ table|safe }}
    {% endfor %}
  </tr>
</table>

Upvotes: 2

Views: 955

Answers (1)

v25
v25

Reputation: 7621

Okay, the first thing to note is that the DataFrame.to_html function generates the full table, so there's no need to put the outer <table></table> tags in your template.

I would approach this by creating a function, which returns a dictionary to be used in the template:

from flask import Flask, render_template
app = Flask(__name__)

# Just define this once
classes = 'w3-table w3-striped w3-border'

def gen_dict(df, title):
    return {'title': title,
            'table': df.head().to_html(classes=classes)
            }

Then in your route, where you have for example df and dfrme as your two dataframes, make a nested dictionary, and pass it to the render_template function with dict unpacking:

@app.route('/')
def index():

    d = {'df1': gen_dict(df, 'First Dataframe'),
         'df2': gen_dict(dfrme, 'Second Dataframe')
         }

    return render_template('index.html', **d)

This then lets you display each table separately in your template, along with the title:

<h1> {{df1.title}} </h1>
{{df1.table|safe}}

Some where else...

<h1> {{df2.title}} </h1>
{{df2.table|safe}}

Adding more dataframes in future, then becomes a case of adding a similar key/value pair to the d dictionary, and editing the template code.

Upvotes: 2

Related Questions