简体   繁体   中英

ChartJS and Flask, how to pass data?

I want to draw a chart using ChartJS and Flask.

I can draw the chart when I set my variables directly into the JS part (ie when data: [1.03, 380.31, 0.0, 18.69, 400.02] ), but not when I pass the data using Flask.

I have checked the variable passed to Flask, and I can show in the browser (with a p tag) that the content of the array is fine: [1.03, 380.31, 0.0, 18.69, 400.02]

The JS code is below, t_gamme and t_badge are both arrays (build in Python using append method):

new Chart(document.getElementById("chart-tps"), {
  type: 'bar',
  data: {
    labels: ["A", "B", "C", "D", "TOTAL"],
    datasets: [{
      label: "Temps gamme (h)",
      backgroundColor: "#3e95cd",
      data: "{{ t_gamme }}"
    }, {
      label: "Temps badgé (h)",
      backgroundColor: "#8e5ea2",
      data: "{{ t_badge }}"
    }]
  },
  options: {
    legend: {
      display: false
    },
    title: {
      display: true,
      text: 'Temps badgé versus temps gamme en heures'
    }
  }
});

I would like avoiding to make an AJAX call to an endpoint for getting these arrays because I have already.

I removed " character and it works, but I have errors in Javascript code in Visual Studio Code: 删除 " 字符时出错

Related to ChesskoWarrior's answer:

I tried that solution, but still, get the red error on double brackets. 双括号错误

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM