# 模板
## 模板
* 模板是HTML頁面,可以根據視圖中傳遞的數據填充值
* 創建模板的模板結構圖

* 修改settings.py文件,設置TEMPLATES的DIR值
```text
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
```
* 在模板中訪問視圖傳遞的數據
```text
{{輸出值,可以是變量,也可以是對象.屬性}}
{%執行代碼%}
```
### 定義index.html模板
```text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
{{ number }}
<h1>學生信息</h1>
<ul>
<li>
<a href="{{student.pk}}">{{ student.pk }}--{{student.stu_name}}--{{ student.stu_date }}</a>
</li>
</ul>
</body>
</html>
```
```text
views.py
"""
def index(request):
student = students.objects.get(pk=1)
# return HttpResponse(student.stu_date)
return render(request,'myapp/index.html',{'student':student})
"""
注意要在urls.py添加路由
urlpatterns = [
url(r'^index/$',views.index),
]
通過localhost:8000/index訪問
```
### 定義detail.html模板
* 在模板中訪問對象成員時,都以屬性的方式訪問,即方法也不能括號
```text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>詳情頁</title>
</head>
<body>
<h1>{{ grade.gra_name }}班</h1>
<ul>
{% for student in grade.students_set.all %}
<li>{{ student.stu_name }} ---- {{student.stu_sex }} --{{ student.stu_date }}</li>
{% endfor %}
</ul>
</body>
</html>
```
* 編譯views.py文件,在方法中調用模板
* django提供了函數Render\(\)簡化視圖調用模板、構造上下文
```text
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext,loader
from .models import grades,students
# Create your views here.
# def index(request):
# return HttpResponse("index")
#
# def detail(request,id):
# return HttpResponse("detail %s" % id)
def index(request,id):
student = students.objects.get(pk=id)
# return HttpResponse(student.stu_date)
return render(request,'myapp/index.html',{'student':student,'id':id})
def detail(request,id):
grade = grades.objects.get(pk=id)
return render(request,'myapp/detail.html',{'grade':grade})
```
```text
urls.py文件配置路由
"""
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index/(\d+)/$',views.index),
url('detail/(\d+)/',views.detail),
]
"""
```
## 去除模板的硬編碼
* 在index.html模板中,超鏈接是硬編碼的,此時的請求地址為"127.0.0.1/index/1"
```text
<a href="{{student.pk}}"}
```
* 如果建urlconf中詳細頁如下,鏈家就找不到了
* ```text
url('^grades/(\d+)/$',views.detail),
```
* 此時請求的地址為"localhost/grades/1"
* 問題:如果在模板中地址硬編碼,將來urlconf修改后,地址將失效
* 解決:使用命名的url設置超鏈接
* 修改"text1/urls.py"文件,在include中設置namespace
```text
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^',include(('myapp.urls',"myapp"),namespace="myapp")),
]
```
修改myapp/url.py文件,設置name
```text
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^index/(\d+)/$',views.index,name="index"),
url('bookdetail/(\d+)/',views.detail,name="detail"),
]
```
可以根據name來進行動態更改
#### render函數
將指定頁面渲染后返回給瀏覽器
render\(request, template\_name\[, context\])
結合一個給定的模板和一個給定的上下文字典,并返回一個渲染后的 HttpResponse 對象。
```text
參數:
request: 用于生成響應的請求對象。
template_name:要使用的模板的完整名稱,可選的參數
context:添加到模板上下文的一個字典。默認是一個空字典。如果字典中的某個值是可調用的,視圖將在渲染模板之前調用它。
content_type:生成的文檔要使用的MIME類型。默認為DEFAULT_CONTENT_TYPE 設置的值。
status:響應的狀態碼。默認為200。
```