#DTL與普通的HTML文件的區別:html
DTL模板是一種帶有特殊語法的HTML文件,這個HTML文件能夠被Django編譯,能夠傳遞參數進去,實現數據動態化。在編譯完成後,生成一個普通的HTML文件,而後發送給客戶端。DTL 是 Django Template Language 三個單詞的縮寫,也就是Django自帶的模板語言。django
#渲染模板函數
-
先在templates文件夾下建立html文件。url
-
render_to_string:找到模板,而後將模板編譯後渲染成Python的字符串格式。最後在經過HttpResponse類包裝成一個HttpResponse對象返回回去。spa
在views.py文件中編寫 from django.template.loader import render_to_string from django.http import HttpResponse def index(request): html = render_to_string("detail.html") return HttpResponse(html) 最後在urls.py文件中,將路徑寫入便可
-
以上方式雖然已經很方便了。可是django還提供了一個更加簡便的方式,直接將模板渲染成字符串和包裝成 HttpResponse 對象一步到位完成。code
在views.py文件中編寫 from django.shortcuts import render der index(request): return render(request,'detail.html')
#模板查找路徑配置htm
模板查找路徑配置:在項目的 settings.py文件中。有一個TEMPLATES 配置,這個配置包含了模板引擎的配置,模板查找路徑的配置,模板上下文的配置等。模板路徑能夠在這個地方配置。對象
-
DIRS:這是一個列表,在這個列表中能夠存放全部的模板路徑,之後在視圖中使用 render或者render_ to _ string渲染模板的時候,會在這個列表的路徑中查找模板。模板引擎
'DIRS':[os.path.join(BASE_DIR, 'templates')]
-
APP_DIRS:默認爲True,這個設置爲 True 後,會在<font color=#FF0000>"INSTALLED _ APPS"</font>的安裝了的 APP下的 templates文件加中查找模板。索引
'APP_DIRS': True,
-
DIRS優先級高於APP_DIRS
#模板變量的使用
模板中能夠包含變量, Django在渲染模板的時候,能夠傳遞變量對應的值過去進行替換。變量的命名規範和Python很是相似,只能是阿拉伯數字和英文字符以及下劃線的組合,不能出現標點符號等特殊字符。變量須要經過視圖函數渲染,視圖函數在使用render或者render_to_string的時候能夠傳遞一個<font color=#FF0000>context </font>的參數,這個參數是一個<font color=#FF0000>字典類型</font>。之後在模板中的變量就從這個字典中讀取值的。
-
views.py代碼示例
def profile(request): return render(request,'profile.html',context={'username':'張三 '})
-
profile.html模板代碼示例
<p>{{username}}</p>
模板中的變量一樣也支持 點(.)的形式。在出現了點的狀況,好比 person.username,模板是按照如下方式進行解析的:
-
views.py示例
class Person(object): def__init__(self,username): self.username = username def profile(request): p = Person('jiajia') #建立一個對象 context = { 'person':p } return render(request,'profile.html‘,context=context)
-
html代碼示例
<html> ... <body> {{person.username}} #根據Key來獲取 </body> </html>
傳遞的一個參數是一個模型或者是一個類。獲取屬性的話。能夠經過點的方式
若是person是一個字典呢?
-
views.py示例
class Person(object): def__init__(self,username): self.username = username def profile(request): context = { 'person':{ 'username':'jiajia' #person對應的是一個字典 } } return render(request,'profile.html,context=context)
-
html代碼示例
{{person.username}}
#注意
若是views.py文件是這樣的。
context = { 'person':{ 'username':'jiajia' #person對應的是一個字典 'keys':'abc' } }
html文件是這樣的呢?
{{person.keys}}
返回的是abc,即對應的值。這樣是會產生歧義的。<font color=#FF0000>爲了不產生歧義,應該避免在這個字典內寫他自己的一些屬性來做爲這個鍵的值!</font>
另外的形式
-
views.py示例
context = { 'person':[ 'a', #這裏是一箇中括號 'b', 'c' ] }
如何獲取列表屬性的第一個值a呢?
-
html代碼示例
{{person.0}} #經過點(.)索引獲取
同理,元組也是這樣。