6.1配置
在工程中創建模板目錄templates。
在settings.py配置文件中修改TEMPLATES配置項的DIRS值:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
6.2模板渲染
Django提供了一個函數render
用法:render(request對象, 模板文件路徑, 模板數據字典)
from django.shortcuts import render
def index(request):
context={
'city': '北京',
'adict': { 'name': '西遊記', 'author': '吳承恩' }, 'alist': [1, 2, 3, 4, 5]
}
return render(request,'index.html',context)
6.3模板語法
模板語法和flask中基本相同,不同的地方如下:
(1)字典的取值方法
{{ adict.name }}
(2)列表的取值方法
{{ alist.0 }} #獲取列表中第0個值
(3)for循環
{% for item in 列表 %}
讀取索引:{{ forloop.counter }} # 表示當前是第幾次循環,從1開始
遍歷爲空:{% empty %} # 列表爲空或不存在時執行此邏輯 {% endfor %}
(4)過濾器
在django中,最多隻能傳一個參數到過濾器