前言
在之前的文章中,視圖函數只是直接返回文本,而在實際生產環境中其實很少這樣用,因為實際的頁面大多是帶有樣式的HTML代碼,這可以讓瀏覽器渲染出非常漂亮的頁面。目前市面上有非常多的模板系統,其中最知名最好用的就是DTL和jinja2。DTL是Django Template Language 三個單詞的縮寫,也就是Django自帶的模板語言。當然也可以配置Django支持jinja2等其他模板引擎,但是作為Django內置的模板語言,和Django可以達到無縫銜接而不會產生一些不兼容的情況。因此建議大家學習好DTL。
一、DEL與普通的HTML文件的區別
DTL模板是一種帶有特殊語法的HTML文件,這個HTML文件可以被Django編譯,可以傳遞參數進去,實現數據動態化。在編譯完成后,生成一個普通的HTML文件,然后發送給客戶端。
二、渲染模板?
Django提供了一個簡便的方式,直接將模板染成字符串和包裝成HttpResponse對象一步到位完成。
1.創建templates文件夾,所有的html模板將放入其中
2.找到settings.py文件將模板路徑輸入其中
'DIRS': [os.path.join(BASE_DIR,'./templates')],
?3.準備HTML模板 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body><h1>我的第一個標題</h1><p>我的第一個段落</p>
</body>
</html>
4.編寫視圖函數
#app應用中 views.py文件
from django.shortcuts import render
#模板應用
def index(request):return render(request,template_name="index.html")
5.編寫路由
#app應用中 urls.py文件
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [path('admin/', admin.site.urls),path('',views.index, name='index')
三、DTL模板語法
1.變量
模板中可以包含變量,Django在渲染模板的時候,可以傳遞變量對應的值過去進行替換。變量的命名規范和Python非常類似,只能是阿拉伯數字和英文字符以及下劃線的組合,不能出現標點符號等特殊字符。變量需要通過視圖函數渲染,視圖函數在使用render或者render_to_string的時候可以傳遞一個context的參數,這個參數是一個字典類型。以后在模板中的變量就從這個字典中讀取值的。
1.編寫視圖函數
#app應用中 views.py文件
#動態傳值
def info(request):#1.普通變量username = '你好,世界'# return render(request,template_name="info.html", context={'username':username})#2.字典類型book = {'name':"水滸傳",'author':'施耐庵'}# return render(request, template_name="info.html", context={'username': username,'book':book})#3.列表類型books = [{'name':'水滸傳','author':'施耐庵'},{'name':'三國演義','author':'羅貫中'}]# context = {# 'username':username,# 'book':book,# 'books':books# }# return render(request, template_name="info.html", context=context)#4.對象class Person:def __init__(self):self.realname = '張安'context = {'username': username,'book': book,'books': books,'person':Person()}return render(request, template_name="info.html", context=context)
2.編寫路由
#app應該中 urls.py文件
from django.contrib import admin
from django.urls import path
from app import viewsurlpatterns = [path('admin/', admin.site.urls),path('',views.index, name='index'),path('info',views.info,name='info')]
3.編寫html文件(info.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body><h1>{{ username }}</h1><h1>{{ book.name }}</h1><h1>{{ books.1.name}}</h1><h1>{{ person.realname}}</h1></body>
</html>
四、常用標簽
1.if標簽
if標簽:if標簽相當于python中的if語句,有elif和else相對應,但是所有的標簽都需要用標簽符號({%%})進行包裹。if標簽中可以使用=、!=、<、<=、>、>=、in、not in、is、is not等運算符
1.編寫視圖函數
#app應用views.py中l
def index(request):age = 20return render(request,template_name='index.html',context={'age':age})
2.編寫路由
#主路由 urls.py
path('if',views.if_,name='if')
3.編寫html
#if.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body>{% if age > 18 %}<p>你可以進去了</p>{% elif age < 18 %}<p>你不可以進去</p>{% endif %}
</body>
</html>
2.for標簽
for...in...標簽:for...in...類似于python中的for...in...。可以遍歷列表、元組、字符串、字典等一切可以遍歷的對象。
1.編寫視圖函數
#app應用 views.py中
def for_(request):#1.列表books = [{'name': '水滸傳', 'author': '施耐庵'},{'name': '三國演義', 'author': '羅貫中'}]#2.字典# for x in person.items/keys/valuesperson ={'realname':"張三","age":18,"height":180}context = {'books':books,"person":person}return render(request,template_name='for.html',context=context)
2.編寫路由
#主路由的urls.py
path('for',views.for_,name='for')
3.編寫html
#for.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body><table><tbody>{% for book in books %}<tr><td>{{ book.name }}</td><td>{{ book.author }}</td></tr>{% endfor %}</tbody>
</table>
<div>{% for key, value in person.items %}<p> {{ key }} : {{ value }} </p>{% endfor %}
</div>
</body>
</html>
如果想要反向遍歷,那么在遍歷的時候就加上一個reversed。
{% for person in persons reversed %}<p>{{ person.name }}</p>
{% endfor %}
在for循環中,DTL提供了一些變量可供使用。這些變量如下:
-
forloop.counter:當前循環的下標。以1作為起始值。
-
forloop.counter0:當前循環的下標。以0作為起始值。 forloop.revcounter:當前循環的反向下標值。比如列表有5個元素,那么第一次遍歷這個屬性是等于5,第二次是4,以此類推。并且是以1作為最后一個元素的下標。
-
forloop.revcounter0:類似于for1oop.revcounter。不同的是最后一個元素的下標是從0開始。
-
forloop.first:是否是第一次遍歷。
-
forloop.last:是否是最后一次遍歷
-
forloop.parentloop:如果有多個循環嵌套,那么這個屬性代表的是上一級的for循環。
3.with標簽
with標簽:在模版中定義變量。有時候一個變量訪問的時候比較復雜,那么可以先把這個復雜的變量緩存到一個變量上,以后就可以直接使用這個變量就可以了。
1.編寫視圖函數
#app應用 views.py中
def with_(request):context ={'books':[{'name': '水滸傳', 'author': '施耐庵'},{'name': '三國演義', 'author': '羅貫中'}]}return render(request,template_name='with.html',context=context)
?2.編寫路由
#主路由中的urls.pypath('with',views.with_,name='with')
3.編寫html
#with.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body>{% with book1 = book.1 %}<p>{{ book1.name }}/{{ book1.author }}</p>
{% endwith %}</body>
</html>
4.url標簽
url標簽:在模版中,我們經常要寫一些url,比如某個a標簽中需要定義href屬性。當然如果通過硬編碼的方式直接將這個url寫死在里面也是可以的。但是這樣對于以后項目維護可能不是一件好事。因此建議使用這種反轉的方式來實現,類似于django中的reverse一樣。
1.編寫視圖函數
#app應用 views.py中
def url_(request):return render(request,template_name='url.html')def book_id(request,book_id):return HttpResponse("您的圖書id:{}".format(book_id))
2.編寫路由
#主路由中的urls.pypath('url',views.url_,name='url'),path('book/int:<book_id>',views.book_id,name='book_id')
3.編寫html
#url.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>你好</title>
</head>
<body><a href="{% url 'for' %}">for.html</a>
<a href="{% url 'book_id' 1 %}">圖書列表</a></body>
</html>