使用瓶子render_template在前端做一个高级图表 [英] using flask render_template to make a highchart on the front end

查看:648
本文介绍了使用瓶子render_template在前端做一个高级图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的python方法,它会生成一个highcharts的json

  @ app.route('/ make / a /图表')
def make_chart():
data = get_data()
c =计数器
对于每个数据:
c ['AGE'] + = 1

$ chart':{
'type':'column'
}
'title':{
'text' :'按年龄排列'
}
'x轴':{
'categories':[x for c in x]
}
'series': {
'name':'Groups By Age',
'data':[c [x] for c in x]
}
}
return render_template 'some_template.html',json = highchart_json)

是否可以使用模板进行渲染,或者是唯一的真正的方法,把它变成一个高分辨率图像,并将其发送到前端? 把JSON作为Javasc放入模板中ript结构:



 < script type =text / javascript> 
var chart_data = {{highchart_json | tojson | safe}};
< / script>

然后你可以在你的JS代码中使用这个客户端。 JSON是JavaScript的一个子集,毕竟,或者至少由Python json 模块生成的JSON是。



这使用 Flask tojson 过滤器,它产生 HTML安全的 JSON值;任何HTML元字符都会使用JSON \uxxxx 转义码进行转义。


I have a simple python method which will generate a highcharts json

@app.route('/make/a/chart')
def make_chart():
  data = get_data()
  c = Counter
  for each in data:
    c['AGE'] += 1

  highchart_json = {
    'chart': {
      'type': 'column'
    }
    'title': {
      'text': 'arranged by age'
    }
    'x-axis': {
      'categories': [x for x in c]
    }
    'series': {
      'name': 'Groups By Age',
      'data': [c[x] for x in c]
    }
  }
  return render_template('some_template.html', json=highchart_json)

is it possible to have it render with a template, or is the only real way to turn it into a highchart by jsonifying it and sendng it to the front end?

解决方案

You can put JSON into a template as a Javascript structure:

<script type="text/javascript">
    var chart_data = {{ highchart_json|tojson|safe }};
</script>

and you can then use this client-side in your JS code. JSON is a subset of JavaScript, after all, or at least the JSON produced by the Python json module is.

This uses the Flask tojson filter, which produces HTML safe JSON values; any HTML-metacharacters are escaped for you using JSON \uxxxx escape codes.

这篇关于使用瓶子render_template在前端做一个高级图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆