環境同上篇django文章。html
啓動django的web服務:python
]# cd py3/django-test1/test4 ]# python manage.py runserver 192.168.255.70:8000
在html模板中,若是要顯示的內容包含html標籤:
web
編輯視圖:django
]# vim bookshop/views.py from django.shortcuts import render from .models import * ... def htmlTest(request): context = {'key1':'<h1>html 轉義</h1>'} return render(request, 'bookshop/htmlTest.html',context)
添加html模板:vim
]# vim templates/bookshop/htmlTest.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> {{ key1 }} </body> </html>
添加應用url路由:瀏覽器
]# vim bookshop/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(\d+)$', views.show, name='show'), url(r'^(\d+)/(\d+)$', views.show, name='show'), url(r'^index2$', views.index2, name='index2'), url(r'^user1', views.user1, name='user1'), url(r'^user2', views.user2, name='user2'), url(r'^htmlTest',views.htmlTest), ]
訪問瀏覽器:http://192.168.255.70:8000/htmlTestbash
顯示:ide
此方式是經過傳遞變量在html模板中顯示,變量key1的值爲<h1>html 轉義</h1>,在傳遞過程當中沒有被轉義爲標籤,而是原封不動的顯示了。url
下面是轉義時是方法:server
修改html模板:使用|safe過濾器爲html轉義
]# vim templates/bookshop/htmlTest.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> {{ key1}} <hr> {{ key1|safe}} </body> </html>
瀏覽器訪問:http://192.168.255.70:8000/htmlTest
顯示:
還可使用{%autoescape%}標籤爲代碼塊的轉義,字面值|default進行轉義,還有經過手動轉義等多種方法:
修改html模板:
<!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> {{ key1}} <hr> {{ key1|safe}} <hr> {% autoescape off %} {{ key1 }} {% endautoescape %} <hr> 字面值 {{t2|default:'<h1>django-html轉義</h1>'}} <br> 手動轉義:{{t2|default:'<h1>轉義</h1>'}} </body> </html>
瀏覽器訪問:http://192.168.255.70:8000/htmlTest
顯示: