简体   繁体   English

使用JavaScript Staticfile将Json从Django传递到模板

[英]Pass Json from Django to template with JavaScript Staticfile

I am trying to pass a json from django to a template html file with javascript staticfile. 我正在尝试使用javascript staticfile从django将json传递到模板html文件。

view.py view.py

import json
def view(request,...)
...
    return render(request,'index.htm',"g1":json.dumps({"id":1,"name":2})

index.html index.html

<head>
<script language=javascript" src="/static/myapp/myscript.js"></script>
</head>
<body onload="init();">
<div>I am here</div>
</body>

myscript.js myscript.js

var json = {{g1}};
function init(){
}

myscript.js is not working. myscript.js无法正常工作。 Without {{g1}} statement in .js file, it works. 在.js文件中没有{{g1}}语句的情况下,它可以工作。 Please help. 请帮忙。

I don't believe the variable will be passed into the myscript.js. 我不相信该变量将被传递到myscript.js中。 You have to add the js inline within the template to get it: 您必须在模板中添加内联js以获取它:

<script>
var json = {{g1}};
function init(){
}
</script>

Also according to other stackoverflow answers, this may be vulnerable to injection attacks if you do not use this: 另外,根据其他stackoverflow答案,如果不使用此命令,则可能容易受到注入攻击:

escapejs filter: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#escapejs escapejs过滤器: https ://docs.djangoproject.com/zh-CN/1.8/ref/templates/builtins/#escapejs

safe filter: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#safe 安全过滤器: https : //docs.djangoproject.com/zh-CN/1.8/ref/templates/builtins/#safe

Other sources: Django Template Variables and Javascript 其他来源: Django模板变量和Javascript

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

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