In my templates/index.html file, I have the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
</style>
</head>
<body>
<div id="graphDiv"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script>
</script>
</body>
</html>
In my app.py file, I have the following code:
import json
from flask import Flask, render_template
import pandas as pd
app = Flask(__name__)
@app.route("/")
def index():
df = pd.read_csv('data.csv').drop('Open', axis=1)
chart_data = df.to_dict(orient='records')
chart_data = json.dumps(chart_data, indent=2)
data = {'chart_data': chart_data}
return render_template("index.html", data=data)
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port =5000)
I decided to move the JavaScript code from the index.html file into a separate directory named static/
, where I stored the style.css
and main.js
files containing the following code:
var graphData = {{ data.chart_data | safe }}
var margin = {top: 30, right: 50, bottom: 30, left: 50};
var svgWidth = 600;
var svgHeight = 270;
var graphWidth = svgWidth - margin.left - margin.right;
var graphHeight = svgHeight - margin.top - margin.bottom;
// More JavaScript code here...
drawGraph(graphData);
However, when running the Flask server, I encountered an error:
SyntaxError: expected property name, got '{'
in the line var graphData = {{ data.chart_data | safe }}
. The strange thing is that this error only occurs when the JavaScript code is not inline in the index.html file. I've tried researching solutions but haven't been able to fix the issue. It's still unclear to me why this error is happening.