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

标签 html flask jinja2 chart.js

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

这是 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有问题。

最佳答案

我遇到了类似的问题。通过用

替换标签和数据部分解决了这个问题
{{labels | tojson}}

{{values | tojson}}

如果它们是列表。

我找到了答案 here

关于html - 无法使用 chart.js 在 Flask/jinja2 html 上加载图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47100622/

相关文章:

html - 为什么类不更新ID?

javascript - HTML 图像映射与多个 div 元素

python - 附加操作按钮在 flask-admin 上不起作用

http - 用于 uWSGI 服务器的 worker 和线程的标准数量是多少?

templates - Ansible 取消保管和模板化文件

javascript - jQuery fadeIn 是即时的大元素

css - HTML5 对 CSS 相对和绝对定位的更改

python - 如何测试 SocketIO 服务器连接(使用 pytest 或任何其他包)?

python - flask 和 WTForms : DatePicker Widget to display a date

python - Jinja2:将十六进制转换为 Base64