1,模版转义的作用
Django模版系统默认会自动转义所有变量。这意味着,如果你在模版中输出一个变量,它的内容会被转义,以防止跨站脚本攻击(XSS)。例如,如果你的变量包含HTML标签,这些标签会被转义,而不是被浏览器解释。
2,添加函数视图
Test/app5/views.py
from django.shortcuts import render# Create your views here.
import datetimedef filter(request):str1 = 'abcdefg'str2 = 'ABCDEFGHIJKLMNO'str3 = '123456789'time_str = datetime.datetime.now()return render(request, '5/filter.html', {'str1':str1, 'str2':str2, 'str3':str3, 'time_str':time_str})def html_filter(request):html_addr = """<table border='2'><tr><td>这是表格A</td><td>这是表格B</td></tr></table>"""html_script = """<script language='JavaScript'>document.write('非法执行');</script>"""return render(request, '5\html_filter.html', {"html_addr":html_addr, "html_script":html_script})
3,添加路由地址
Test/app5/urls.py
from django.urls import path
from . import viewsurlpatterns = [path('filter', views.filter, name='filter'),path('html_filter', views.html_filter, name='html_filter'),]
4,添加html代码
Test/templates/5/html_filter.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>关闭模版转义-表格: {{ html_addr|safe }}
默认模版转义-表格: {{ html_addr }}<br>
默认模版转义-脚本: {{ html_script }}<br>
关闭模版转义-脚本: {{ html_script|safe }}<br><!--{{ html_addr }}--><!--{{ html_script }}-->
<!--{{ html_script|safe }}--></body>
</html>
5,访问页面
http://127.0.0.1:8000/app5/html_filter
Django 页面上直接显示了 “{{ html_addr|safe }}“ 和 “{{ html_script|safe }}“-CSDN博客