As the question states, I simply want to pass and render the results of a list (passed from the main.py file in a flask project) to a html template (charts.html). The issue is that I am trying to put the jinja variable or use jinja inside of script tags (JavaScript) and not the html. I cannot find any documentation or answers that tell me how to do this:
My code: charts.html (template in flask)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<title>Webscraping and Charts</title>
</head>
<body>
<h1>Webscraping and Beautiful Charts</h1>
<p>{{enrolled}}</p>
<div class="ct-chart .ct-perfect-fifth"></div>
<script>
var data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[15, 222, 4, 2, 0]
]
};
new Chartist.Line('.ct-chart', data); //this line creates the chart
</script>
</body>
</html>
Under the h1 tag, you'll notice:
{{enrolled}}
The contents of this variable is defined in the python file. Function showed below. enrolled=[3,200,600,1800,22000]
@app.route('/charts')
def charts():
enrolled=[3,200,600,1800,22000]
return render_template('charts.html',enrolled=enrolled)
What I would like is for the contents of enrolled to be displayed instead of the existing list in the script tags.
So, replace [15, 222, 4, 2, 0] in the script tags with the contents of enrolled.
I have tried various things, and it does not work.
For instance, I tried putting the jinja variable inside the list that renders the list like below.
<script>
var data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[{{enrolled}}]
]
};
new Chartist.Line('.ct-chart', data); //this line creates the chart
</script>
This doesn't work.
Can anyone suggest a solution with an explanation for best practices when trying to use jinja2 inside of JavaScript to render data to an html page, in this case list data for a chart using chartist.js
Update:
I have also researched a solution that involves using jquery and ajax to render the results (no jinja2 used at all), but this seems overly complex for what I am trying to achieve.
Please, in your answers, suggest the best solutions/alternatives but my main question is whether or not it can be easily achieved using jinja2