I want to know what the best practice is for my application project.
I want to render a chart using Chart.js. Data is generated in Python, and I know how to pass it to html: render_template("/index.html", chart_data=chart_data). However, after passing chart_data to html, I don't know how to pass it to the javascript, where the chart is generated. Or, is it better to pass it directly from .py to .js, without bypassing .html? If so, what is the way?
Here are my codes: app.py
import os
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
# Configure application
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
chart_data = {
"labels": ["Italy", "France", "Spain", "USA", "Argentina"],
"values": [55, 49, 44, 24, 15]
}
return render_template("/index.html", chart_data=chart_data)
if __name__ == "__main__":
app.run()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.2/chart.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<canvas id="myChart" style="width:100%;max-width:700px"></canvas>
<script type="text/javascript" src="static/app.js"></script>
</div>
</body>
</html>
app.js
// For the testing purpose, I generated the same data in js.
// But I want to fetch this from .html, or directly from .py.
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = ["red", "green", "blue", "orange", "brown"];
let myChart = document.getElementById('myChart').getContext('2d');
let barChart = new Chart(myChart, {
type: 'bar',
data: {
labels: xValues,
datasets: [
{
label: "population",
data: yValues
}
]
},
options: {}
});
As a side note, this is a minimal reproducible example from my entire project. In the real project, my app.py gets user inputs from index.html using request.form.get() and dynamically generates chart_data. But I excluded this part from the question because I was able to make it work.
EDIT
In the app.js, I modified like below but it seems this syntax is only supported in .html. I don't want to include my js script in html, but instead have it as a separated .js file.
data: {
labels: {{ chart_data['labels']| tojson }},
datasets: [
{
label: "population",
data: {{ chart_data['values']| tojson }}
}
]
}