How to show a table with Tabulator using Flask and a JSON variable

Viewed 463

I am starting with both Flask and JQuery, and I need some help. I want to display a table (which I want to become dynamic later), but I don't find how to link the table (JSON) I put in parameter in a render_template, and the table I would like to show on my html page by using Tabulator.

Here is my app.py :

import os
from flask import Flask, render_template
import pandas as pd
import excel2json

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'upload_folder'

df = pd.read_excel(os.path.join(app.config['UPLOAD_FOLDER'], "file.xlsx"), engine="openpyxl")
df = df.to_json()

@app.route('/')
def index():
   return render_template('index.html', tables=df)

This work like I want (I transform df into a Json for later, this is not my problem)

<html>
  <head>
    <script src='static/jquery.js'></script>
    <script src='static/jquery-ui.js'></script>
    <link rel='stylesheet' href='static/tabulator.css'>
    <script src='static/tabulator.js'></script>
  </head>

  <body>

  <div id='example-table'>
    <script type='text/javascript'>

      var table = new Tabulator(#example-table, {
      columns:[
      {title:"col1", field="col1"},
      {title:"col2", field="col2"},
      {title:"col3", field="col3"}
      ]
      });

      var tabledata = tables.getData();

    </script>
  </body>

When I use :

var tabledata = [
{col1:0, col2:3, col3:6},
{col1:1, col2:4, col3:7},
{col1:2, col2:5, col3:8}
]

it works

But obviously, my last part doesn't work. My question is : how to put the parameter tables (app.py) in tabledata ?

The format of tables is : tables= {"col1":{0,1,2}, "col2":{3,4,5}, "col3":{6,7,8}}

Thank you for your help :)

1 Answers

You can pass on the loaded data as a dict to the template with specific orientation.

@app.route('/')
def index():
   src = os.path.join(app.config['UPLOAD_FOLDER'], 'file.xlsx')
   df = pd.read_excel(src, engine='openpyxl')
   return render_template('index.html', data=df.to_dict(orient='records')

Then the data is converted into a javascript compliant variant with the help of the jinja2 filter tojson.

<html>
  <head>
    <link href="https://unpkg.com/tabulator-tables@4.1.4/dist/css/tabulator.min.css" rel="stylesheet">
    <script type="text/javascript" src="https://unpkg.com/tabulator-tables@4.1.4/dist/js/tabulator.min.js"></script>
  </head>
  <body>
    <div id="example-table"></div>
    <script type="text/javascript">
      const tabledata = {{ data | tojson }};
      const table = new Tabulator(
        "#example-table",
        {
          data:tabledata,
          columns:[
            {title:"col1", field:"col1"},
            {title:"col2", field:"col2"},
            {title:"col3", field:"col3"}
          ]
        }
      );
    </script>
  </body>
</html>

As long as the defined columns match the information within the data, the table should appear as desired.

Related