Reputation: 6159
I'm using ChartJs to display some data, my chart is defined like so:
var myChart = new Chart(ctx1, {
type: 'pie',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
label: 'Chart 1',
data: [12, 19, 100, 5],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1
}]
},
options: {
}
});
The variable label
I would like to populate with keys from a python dictionary
chart_data = {'A':10, 'B':5, 'C':7, 'D':15}
and the data
variable populated with the dictionary values, so what I'd end up with in my javascript is
labels: ['A', 'B', 'C', 'D'],
datasets: [{
label: 'Chart 1',
data: [10, 5, 7, 15],
I'm just not sure how to iterate a dictionary with Jinja to only return the keys, and to only return the values, into a JavaScript list.
Can I use a Jinja for/loop to iterate inside a javascript list? It doesnt seem to work
some_js_var = [{% for x in y %} {{ x }} {% endfor %}]
Upvotes: 0
Views: 1115
Reputation: 6159
I assigned my python dictionary to a JS variable like so:
var data_from_python = {{ python_dict|tojson }}
Then to just assign the keys to a variable as a list:
labels: Object.keys(data_from_python),
and same the values in the data
data: Object.values(data_from_python)
What I end up with is
labels: ['A', 'B', 'C', 'D']
data: [10, 5, 7, 15]
Upvotes: 1