using flask render_template to make a highchart on the front end

我是研究僧i 提交于 2019-12-17 07:53:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/22620544/using-flask-render-template-to-make-a-highchart-on-the-front-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!