1,定義
在Django中,將前端的內容定義在模板中,然后再把模板交給視圖調用,各種漂亮、炫酷的效果就出現了。
2,創建模板
為應用booktest下的視圖index創建模板index.html,目錄結構如下圖:
這里寫圖片描述
設置查找模板的路徑:打開test1/settings.py文件,設置TEMPLATES的DIRS值
'DIRS': [os.path.join(BASE_DIR, 'templates')],
這里寫圖片描述
3,定義模板
打開templtes/booktest/index.html文件,在里面寫模板代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試模板</title>
</head>
<body>
<h1>我是測試模板文件</h1><br/>
模板變量:{{content}}<br/>
使用列表:{{list}}<br/>
<ul>
{% for i in list%}
<li>{{i}}</li>
{% endfor %}
</ul>
</body>
</html>
4,視圖調用模板
調用模板分為三步驟:
- 1.找到模板
- 2.定義上下文
- 3.渲染模板
打開booktest/views.py文件,調用上面定義的模板文件
from django.http import HttpResponse
from django.template import loader,RequestContext
def index(request):
# 1.獲取模板
template=loader.get_template('booktest/index.html')
# 2.定義上下文
context=RequestContext(request,{'content':'hello python','list':range(0,6)})
# 3.渲染模板
return HttpResponse(template.render(context))
這里寫圖片描述
5,視圖調用模板簡寫(推薦這種)
視圖調用模板都要執行以上三部分,于是Django提供了一個函數render封裝了以上代碼。 方法render包含3個參數:
第一個參數為request對象
第二個參數為模板文件路徑
第三個參數為字典,表示向模板中傳遞的上下文數據
打開booktest/views.py文件,調用render的代碼如下:
from django.shortcuts import render
def index(request):
context={'content':'hello python','list':range(0,6)}
return render(request,'booktest/index.html',context)