在django模板中使用JSON

Bre*_*den 6 django django-templates django-template-filters

我有一个包含JSON的变量,我需要传递给模板.我将其定义为变量,然后将其成功传递到模板中.但是,我需要格式用"替换引号",但是替换为'.这会导致我将此传递给服务的问题.

image_upload_params = 
{
  "auth": {
    "key": "xxx"
  },
  "template_id": "xxx",
  "redirect_url": "url-here",
}
Run Code Online (Sandbox Code Playgroud)

以下是模板中的内容:

{'redirect_url': 'url-here', 'template_id': 'xxx', 'auth': {'key': 'xxx'}}
Run Code Online (Sandbox Code Playgroud)

任何想法如何让它使用"而不是?

Ben*_*hon 21

Django 2.1添加了json_script模板过滤器:

安全地将 Python 对象输出为 JSON,包装在标签中,准备与 JavaScript 一起使用

将此插入到您的模板中:

{{ value|json_script:"hello-data" }}
Run Code Online (Sandbox Code Playgroud)

它呈现为:

<script id="hello-data" type="application/json">{"hello": "world"}</script>
Run Code Online (Sandbox Code Playgroud)

然后,您可以安全地将此对象加载到 JavaScript 变量中:

var value = JSON.parse(document.getElementById('hello-data').textContent);
Run Code Online (Sandbox Code Playgroud)

这种方法比简单地编写更安全,var value = {{value|safe}};因为它可以保护您免受 XSS 攻击(更多信息请参见本票)。


zee*_*kay 14

用途SafeString:

from django.utils.safestring import SafeString

def view(request):
    ...
    return render(request, 'template.html', {'upload_params': SafeString(json_string)})
Run Code Online (Sandbox Code Playgroud)