Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

javascript - using flask render_template to make a highchart on the front end

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...