无法使用chart.js在Flask / jinja2 html上加载图表

时间:2017-11-03 16:43:03

标签: html flask jinja2 chart.js

我在一个简单的Bootstrap html文件中有以下代码,它显示了Chart.js图表​​。

这是chart.html

<head>
   <meta charset="utf-8" />
   <title>Chart.js </title>

   <!-- import plugin script -->
   <script src='app/static/js/Chart.min.js'></script>
 </head>

<body>

<div class="chartjs"> 
<h1>Flask Chart.js</h1>
<!-- bar chart canvas element -->
<canvas id="chart" width="600" height="400"></canvas>
</div>

<script>

   // bar chart data
   var barData = {
   labels : [{% for item in labels %}
              "{{item}}",
          {% endfor %}],
   datasets : [
      {
        fillColor: "rgba(151,187,205,0.2)",
        strokeColor: "rgba(151,187,205,1)",
        pointColor: "rgba(151,187,205,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(151,187,205,1)",
        bezierCurve : false,
        data : [{% for item in values %}
                  {{item}},
                {% endfor %}]
      }]
   }

    Chart.defaults.global.animationSteps = 50;
    Chart.defaults.global.tooltipYPadding = 16;
    Chart.defaults.global.tooltipCornerRadius = 0;
    Chart.defaults.global.tooltipTitleFontStyle = "normal";
    Chart.defaults.global.tooltipFillColor = "rgba(0,0,0,0.8)";
    Chart.defaults.global.animationEasing = "easeOutBounce";
    Chart.defaults.global.responsive = false;
    Chart.defaults.global.scaleLineColor = "black";
    Chart.defaults.global.scaleFontSize = 16;

   // get bar chart canvas
   var mychart = document.getElementById("chart").getContext("2d");

   steps = 10
   max = 10

   // draw bar chart
   var LineChartDemo = new Chart(mychart).Line(barData, {
    scaleOverride: true,
    scaleSteps: steps,
    scaleStepWidth: Math.ceil(max / steps),
    scaleStartValue: 0,
    scaleShowVerticalLines: true,
    scaleShowGridLines : true,
    barShowStroke : true,
    scaleShowLabels: true,
    bezierCurve: false,

   });


</script>

</body>

Chart.min.js的方向

enter image description here

事实证明chart.js不起作用

enter image description here

这是与chart.html

有关的views.py的一部分
@main.route('/chart', methods=['GET', 'POST'])
def chart():
labels = ["January","February","March","April","May","June","July","August"]
values = [10,9,8,7,6,4,7,8]
return render_template('chart.html', values=values, labels=labels)

我怀疑是否没有正确引用js并且chart.html出现了问题。

1 个答案:

答案 0 :(得分:0)

我有类似的问题。它是通过用

替换标签和数据部分来解决的
{{labels | tojson}}

{{values | tojson}}

如果他们是名单。

我找到了答案here