使用Jinja将数据作为JSON对象从Python发送到Javascript [英] sending data as JSON object from Python to Javascript with Jinja

查看:1459
本文介绍了使用Jinja将数据作为JSON对象从Python发送到Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个lat / long点作为JSON对象从Python发送到javascript。我正在使用Flask,所以以下是Jinja模板..

I'm trying to send a lat/long point as a JSON object from Python to a javascript. I'm using Flask so the following is Jinja templating..

Python:

@app.route('/')
def homepage():
    lat_lng = (39.7392,-104.9847) 
    return render_template("index_v2.html", lat_lng=json.dumps(lat_lng))

html with js:

html with js:

<script type='text/javascript'>
    var map;
    function initialize() {
      // Create the map.
      var lat_lng = eval('({{ lat_lng }})')
      map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 8,
        center: new google.maps.LatLng(lat_lng)
      });

    }

    google.maps.event.addDomListener(window, 'load', initialize);
  </script>

我正在使用eval,因为变量的标准Jinja符号= {{data}} isn'工作,我发现一些建议,eval是必要的。有什么建议吗?

I'm using the eval because the standard Jinja notation of variable = {{ data }} isn't working and I found some advice that eval was necessary. Any advice?

推荐答案

Flask Jinja2文档非常清楚。 标准过滤器部分下的第一个示例显示了如何将来自python的JSON对象嵌入到Javascript脚本中:

The Flask Jinja2 documentation covers this pretty well. The first example under the "Standard Filters" section shows exactly how to embed a JSON object from python into a Javascript script:

<script type=text/javascript>
    doSomethingWith({{ user.username|tojson|safe }});
</script>

所以在这种情况下:

var lat_lng = {{ lat_lng|tojson|safe }};

tojson 来电对数据进行转储,因此您应该将数据直接传递给模板,而不是在其上调用 dumps ,否则您需要对数据进行双重序列化,最后得到一个JSON字符串。

tojson calls dumps on the data, so you should pass the data directly to the template rather than calling dumps on it, otherwise you double-serialize the data and end up with a JSON string.

这篇关于使用Jinja将数据作为JSON对象从Python发送到Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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