0
点赞
收藏
分享

微信扫一扫

Django-4.3HTML转义-笔记

HTML转义

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

小于号< 转换为 <

大于号> 转换为 >

单引号' 转换为 '

双引号" 转换为 "

与符号& 转换为 &

示例

1)打开booktest/views.py文件,创建视图html_escape。

def html_escape(request):
context={'content':'<h1>hello world</h1>'}
return render(request,'booktest/html_escape.html',context)

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

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

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

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

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

http://127.0.0.1:8000/html_escape/

转义后标记代码不会被直接解释执行,而是被直接呈现,防止客户端通过嵌入js代码攻(敏感词)击网站.

浏览效果如下图:

Django-4.3HTML转义-笔记_html

关闭转义

过滤器escape可以实现对变量的html转义,默认模板就会转义,一般省略。

{{t1|escape}}

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

{{data|safe}}

1)修改templates/booktest/html_escape.html代码如下。

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

刷新浏览器后效果如下图:

Django-4.3HTML转义-笔记_html_02

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

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

1)修改templates/booktest/html_escape.html代码如下。

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

刷新浏览器后效果如下图:

Django-4.3HTML转义-笔记_硬编码_03

字符串字面值

对于在模板中硬编码的html字符串,不会转义。

1)修改templates/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)刷新浏览器后效果如下图:

Django-4.3HTML转义-笔记_html_04

如果希望出现转义的效果,则需要手动编码转义。

1)修改templates/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:"<b>123</b>"}}
</body>
</html>

2)刷新浏览器后效果如下图:

Django-4.3HTML转义-笔记_转义_05

举报

相关推荐

0 条评论