my flask code section that have issue main.py
from flask import Flask, render_template, url_for
import pandas as pd
import json
app = Flask(__name__)
@app.route('/')
def home():
df = pd.read_csv('test.csv')
df = df.groupby('name')['marks'].sum()
j = df.to_json(orient='index')
return render_template("work.html",s=j)
if __name__ == "__main__":
app.run(debug=True)
and i want to pass j into my javascript file that is look like that work.js
//pie chart
var s = {{ j|safe }};
var keys = [];
for(var k in s) keys.push(k);
var value = [];
for (var k in s) value.push(s[k]);
var data = [{
values: value,
labels: keys,
type: 'pie'
}];
var layout = {
height: 400,
width: 500
};
Plotly.newPlot('myDiv1', data);
work.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="navbar"><span>data representation with Plotly.js</span></div>
<div class="wrapper">
<div id="myDiv1"></div>
<script type="text/javascript" src={{ url_for('static', filename='work.js')}}>
</script>
</div>
</body>
</html>
how to pass j variable in flask to s variable in javascript file that render with html page and show right content or say that no graph shown Thank you
sin the JS script is in fact a (JSON) string. Trys = JSON.parse(s)before the loops.work.htmltemplate get the{{s|tojson}}converted to the actual value. This will work if this is in a script tag in the template though (which is what I assumed when I first read your post).