Django-HTML转义

HTML转义
模板对上下文传递的字符串进行输出时,会对以下字符自动转义。

小于号< 转换为 &lt;

大于号> 转换为 &gt;

单引号' 转换为 &#39;

双引号" 转换为 &quot;

与符号& 转换为 &amp

示例
1)打开booktest / views.py文件,创建视图html_escape。def html_escape(request):

context={‘content’:‘

hello world

’}
return render(request,‘booktest/html_escape.html’,context

)
2)打开booktest / urls.py文件,配置网址。

url(r’^html_escape/$’, views.html_escape),

3)在模板/ booktest /目录下创建html_escape.html。

<html>
<head>
    <title>转义</title>
</head>
<body>
自动转义:{{content}}
</body>
</html>

4)运行服务器,在浏览器中输入如下网址。

http://127.0.0.1:8000/html_escape/

转义后标记代码不会被直接解释执行,而是被直接呈现,防止客户端通过嵌入JS代码攻击网站。

浏览效果如下图:
在这里插入图片描述
关闭转义
过滤器逃逸可以实现对变量的HTML转义,默认模板就会转义,一般省略。

{{t1|escape}}

过滤器安全:禁用转义,告诉模板这个变量是安全的,可以解释执行。

扫描二维码关注公众号,回复: 4586728 查看本文章
{{data|safe}}

1)修改的模板/ booktest / html_escape.html代码如下。

<html>
<head>
    <title>转义</title>
</head>
<body>
自动转义:{{content}}
<hr>
过滤器safe关闭转义:{{content|safe}}
</body>
</html>

刷新浏览器后效果如下图:
在这里插入图片描述

标签autoescape:设置一段代码都禁用转义,接受开,关参数。

{%autoescape off%}
...
{%endautoescape%}

1)修改的模板/ booktest / html_escape.html代码如下。

<html>
<head>
    <title>转义</title>
</head>
<body>
自动转义:{{content}}
<hr>
过滤器safe关闭转义:{{content|safe}}
<hr>
标签autoescape关闭转义:
{%autoescape off%}
{{content}}
{%endautoescape%}
</body>
</html>

刷新浏览器后效果如下图:在这里插入图片描述
字符串字面值
对于在模板中硬编码的HTML字符串,不会转义。

1)修改的模板/ booktest / html_escape.html代码如下:

<html>
<head>
    <title>转义</title>
</head>
<body>
自动转义:{{content}}
<hr>
过滤器safe关闭转义:{{content|safe}}
<hr>
标签autoescape关闭转义:
{%autoescape off%}
{{content}}
{%endautoescape%}
<hr>
模板硬编码不转义:{{data|default:'<b>hello</b>'}}
</body>
</html>

2)刷新浏览器后效果如下图:
在这里插入图片描述
如果希望出现转义的效果,则需要手动编码转义。

1)修改的模板/ booktest / html_escape.html代码如下:

<html>
<head>
    <title>转义</title>
</head>
<body>
自动转义:{{content}}
<hr>
过滤器safe关闭转义:{{content|safe}}
<hr>
标签autoescape关闭转义:
{%autoescape off%}
{{content}}
{%endautoescape%}
<hr>
模板硬编码不转义:{{data|default:'<b>hello</b>'}}
<hr>
模板硬编码手动转义:{{data|default:"&lt;b&gt;123&lt;/b&gt;"}}
</body>
</html>

2)刷新浏览器后效果如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43308242/article/details/85156365