从Django模板中转义JSON数据的正确方法
我想将字典从Django视图传递到javascript文件.该词典是根据站点用户填充的数据库构建的.这两种方法在安全性上有什么区别?
I want to pass a dictionary from django view to a javascript file. The dictionary is built from a database populated by site users. What's the difference between these 2 methods in terms of security?
-
var mydata = JSON.parse("{{mydata|escapejs}}");
var mydata = {{ mydata|safe }};
此外,django上的 doc 表示: escapejs
:这不会使字符串在HTML中安全使用.您能给我看一个不安全的例子吗?我该如何确保它安全?
Further, the doc at django says this for escapejs
: This does not make the string safe for use in HTML. Could you show me an example of how it's unsafe & how can I make it safe.
以下字典可能会在没有适当转义的情况下中断您的页面:
The following dictionary can break your page without proper escaping:
{'x':'</script><b>HELLO</b>'}
内部标签,您可以在视图中json.dumps
进行标记,然后使用escapejs
保持安全.
Inside tags, you can json.dumps
it in your view and then use escapejs
to stay safe.
(我相信解释的意思是,如果要在HTML中显示json.dumps
的输出,可以在<pre>
标记中说,只需确保不使用safe
或escapejs
将其转义即可. )
(I believe the explanation means that if you want to show the output of json.dumps
in HTML, let's say in a <pre>
tag, just make sure it is escaped by not using safe
or escapejs
.)