前端使用flask render_template制作highchart [英] using flask render_template to make a highchart on the front end

查看:30
本文介绍了前端使用flask render_template制作highchart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

是否可以使用模板渲染它,或者是通过将其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?

推荐答案

可以将 JSON 作为 Javascript 结构放入模板中:

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

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

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

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.

这使用 Flask tojson 过滤器,生成HTML 安全 JSON 值;使用 JSON uxxxx 转义码为您转义任何 HTML 元字符.

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

这篇关于前端使用flask render_template制作highchart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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