4👍
Here is an example that works for me:
1.) Python function in routes.py as part of the Flask-App:
def index():
data = {"labels": ['a', 'b', 'c', 'd'],
"data_1": [1, 2, 3, 4],
"data_2": [5, 6, 7, 8]}
return render_template('template.html', data=data)
2.) You can access this variable in template.html as {{ variable }}. This works in JS too. However, you need to create a new JS variable and make sure the data is formatted in the right way. Fortunately, there is a Jinja "tojson"-filter which converts the data into a proper JSON (https://flask.palletsprojects.com/en/1.1.x/templating/#standard-filters). Knowing this, this code snippet works for me inside the template.html:
{% block javascripts %}
<script>
var data_js = {{ data|tojson }};
...
});
</script>
{% endblock javascripts %}
Now you can access the data using the original keys:
datasets: [{
label: data_js["labels"],
data: data_js["data_1"]
}, {
label: data_js["labels"],
data: data_js["data_2"]
}]
- [Chartjs]-Add info for points in line chart (js)
- [Chartjs]-Uncaught TypeError: Cannot read property 'draw' of undefined : Angular chart js
Source:stackexchange.com