Django 之----模版的使用
阿新 • • 發佈:2019-02-01
模版的使用
ONE Goal , ONE Passion!
如果對Django基本配置還是小白的話,請移步:
第一:在setting中配置模版資料夾
My_Django/setting.py
TEMPLATES = [ #模版
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')] # 模版資料夾
....
],
},
]
第二:編寫一個模版html
templates/hello/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <ul> {% for item in list%} <li>{{ item }}</li> {% endfor %} </ul> </body> </html>
第三:使用檢視函式返回模版
Django提供了一個函式render封裝了以上程式碼 方法render包含3個引數
- 第一個引數為request物件
- 第二個引數為模板檔案路徑
- 第三個引數為字典,表示向模板中傳遞的上下文資料
hello/views.py:
from django.http import HttpResponse, request
from django.shortcuts import render
'''
定義了一個試圖函式
requset : 請求的request
'''
def hello(request):
# 傳遞給模板的資料
context = {'title': '我是模板', 'list': range(10)}
return render(request, 'hello/index.html', context)
#return HttpResponse("你好,我是模組!")