Javascript Django:将 JSON 从视图传递到模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31151229/
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
Django: passing JSON from view to template
提问by jkarimi
In views.py
, I have time series data stored in a dictionary as follows:
在 中views.py
,我将时间序列数据存储在字典中,如下所示:
time_series = {"timestamp1": occurrences, "timestamp2": occurrences}
where each timestamp
is in unix time and occurrences
is an integer.
其中每个timestamp
都在 unix 时间并且occurrences
是一个整数。
Is there a way to pass the time series data as a json object in the context of the render
function?
有没有办法在render
函数的上下文中将时间序列数据作为 json 对象传递?
Why do this:I am using Cal-heatmapon the front end which requires the data to be in json format. Ajax requests work just fine for now but I ideally would like to use the render
approach if possible.
为什么这样做:我在前端使用Cal-heatmap,它要求数据采用 json 格式。Ajax 请求现在工作得很好,但render
如果可能的话,我希望使用这种方法。
回答by Yuji 'Tomita' Tomita
If a frontend library needs a to parse JSON, you can use the json
library to convert a python dict to a JSON valid string. Use the escapejs
filter
如果前端库需要解析 JSON,您可以使用该json
库将 python dict 转换为 JSON 有效字符串。使用escapejs
过滤器
import json
def foo(request):
json_string = json.dumps(<time_series>)
render(request, "foo.html", {'time_series_json_string': json_string})
<script>
var jsonObject = JSON.parse('{{ time_series_json_string | escapejs }}');
</script>
回答by Romeo Mihalcea
have you tried passing something like json.dumps(time_series)
to the render function?
你有没有试过将类似的东西传递json.dumps(time_series)
给渲染函数?
回答by Milan Cermak
Pass a json.dumps
value to the template. It is already a valid JSON string so you don't need to parse it or anything. Only when rendering it in the template, mark it as safe
to prevent HTML quoting.
将json.dumps
值传递给模板。它已经是一个有效的 JSON 字符串,所以你不需要解析它或任何东西。仅在模板中渲染时,将其标记为safe
以防止 HTML 引用。
# views.py
def foo(request):
time_series_json = json.dumps(time_series)
return render(request,
"template.html",
context={'time_series': time_series_json})
# in the template
<script>
const timeSeries = {{ time_series | safe }};
</script>