0

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 %}]

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.