我想使用 Flask 来呈现 ChartJS 图形。这是来自我的 routes.py
@app.route("/graph")
def graph():
d = Eval.query.all()
labels = [i.date.strftime('%d.%m.%Y') for i in d]
data = [i.bw for i in d]
return render_template('chart.html', title='Charts', labels = labels, data = data)
我在chart.html中有以下代码:
{% extends "base.html" %}
{% block content %}
<canvas id="myChart" height="400" width="800"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<script type="text/javascript">
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['16.07.2017', '23.07.2017', '30.07.2017', '06.08.2017', '13.08.2017'],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: {{ data }}
}]
},
options: {
responsive:false
}
});
</script>
{% endblock %}
使用此代码,图表以正确的标签呈现。
问题:
但是,一旦我将标签更改为
labels: {{ labels }}
图表根本没有呈现。
我检查以确保 {{ labels }} 表达式确实也是具有正确格式的列表。在脚本标签上方调用 {{ labels }} 会在 html 页面中显示以下输出:
['16.07.2017', '23.07.2017', '30.07.2017', '06.08.2017', '13.08.2017']
如果您不使用safe
过滤器,特殊符号将在模板解析过程中被转义,并会破坏变量值。
在上述情况下,没有 'jinja safe' 过滤器的最终变量值将是
["16.07.2017", "23.07.2017"] =>['16.07.2017','23.07.2017']
并且该值 ( ['16.07.2017','23.07.2017']
) 对于 JS 是非法的,您将能够在浏览器控制台中看到错误:
Uncaught SyntaxError: Unexpected token &
在上述情况下,带有“jinja safe”过滤器的最终变量值将相同
["16.07.2017", "23.07.2017"] =>["16.07.2017", "23.07.2017"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句