简体   繁体   English

从views.py获取Django Python数据到template.html中的javascript对象

[英]Getting Django Python data from views.py to javascript object in template.html

I'm using Django's render_to_response to write data out to an html page, but I'd also like that render_ to _response call to load a python dictionary into a javascript associative array. 我正在使用Django的render_to_response将数据写出到html页面,但我也想通过render_ to _response调用将python字典加载到javascript关联数组中。 What's the best way to do this? 最好的方法是什么?

Convert it to JSON and include, in your template.html, inside a <script> tag, something like 将其转换为JSON,并在template.html中的<script>标记内添加类似

var my_associative_array = {{ json_data }}

after having JSON-encoded your Python dict into a string and put it in the context using key json_data . 在将您的Python dict进行JSON编码后,使用键json_data将其放入上下文中。

Vinay Sajip已经关闭,但是您添加了安全过滤器,以避免django自动转义json数据,因此这可以工作(还有其他方法可以停止自动转义,但这是最简单的方法):

 var my_associative_array = {{ json_data|safe }}

What does that mean exactly? 这到底是什么意思? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. 如果您认为模板中的数据是JavaScript术语,则不是:您可以直接在模板中使用python对象。 If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django. 如果您的意思是,如何将Python字典或列表中的JSON文字嵌入我的模板中:使用Django随附的simplejson对其进行编码。

But, you often don't want to do this for a couple reasons. 但是,由于多种原因,您通常不想这样做。 If you include this dynamic data in the template, you can't cache it as easily. 如果在模板中包含此动态数据,则无法轻松地对其进行缓存。 Shouldn't this be another view that is generating a JS file you're including? 这不应该是另一个正在生成您要包含的JS文件的视图吗? Or maybe an AJAX call to grab the data once the page is live? 还是在页面上线后通过AJAX调用来获取数据? Take the pick for what best fits you situation. 选择最适合您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM