使用 Jinja 将数据作为 JSON 对象从 Python 发送到 Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24719592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:04:15  来源:igfitidea点击:

sending data as JSON object from Python to Javascript with Jinja

javascriptpythonjsonpython-2.7jinja2

提问by tesslins

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..

我正在尝试将纬度/经度点作为 JSON 对象从 Python 发送到 javascript。我正在使用 Flask 所以以下是 Jinja 模板..

Python:

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:

带js的html:

<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>

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?

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

回答by Dennis L

The Flask Jinja2 documentationcovers 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:

Flask Jinja2 文档很好地涵盖了这一点。“标准过滤器”部分下的第一个示例准确显示了如何将 Python 中的 JSON 对象嵌入到 Javascript 脚本中:

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

So in this case:

所以在这种情况下:

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

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

tojson调用dumps数据,所以你应该将数据直接传递给模板而不是调用dumps它,否则你对数据进行双重序列化并最终得到一个 JSON 字符串。