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

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

问题描述

我正在尝试将纬度/经度点作为 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..

蟒蛇:

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

带有 js 的 html:

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 是因为变量 = {{ data }} 的标准 Jinja 符号不起作用,我发现一些建议 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?

推荐答案

The 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,所以你应该将数据直接传递给模板而不是调用 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天全站免登陆