【Django02】Django模板
通過django.http.HttpResponse() 來輸出 “Hello World!”,這種方式將資料與試圖混合在一起,不符合Django的MVC思想。
Django模板是一個文字,用於分離文件的表現形式和內容。
模板應用例項
#在HelloWorld目錄下建立templates目錄並建立hello.html檔案。
#hello.html
<h1>{{ hello }}</h1>
#從模板中我們知道了變數使用雙括號
#接下來我們需要向Django說明模板檔案的路徑,修改HelloWorld/settings.py,修改 TEMPLATES 中的 DIRS 為 [BASE_DIR+"/templates",]
#settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
#通過修改view.py,增加一個新的物件,用於向模板提交資料
#view.py
from django.shortcuts import render
def hello(request):
context = {}
context[ 'hello'] = 'Hello Xuhuan!'
return render(request, 'hello.html', context)
#可以看到,我們這裡使用 render 來替代之前使用的 HttpResponse。render 還使用了一個字典 context 作為引數。
#context 字典中元素的鍵值 "hello" 對應了模板中的變數 "{{ hello }}"。
#這樣我們就完成了使用模板來輸出資料,從而實現資料與檢視分離。
Django模板標籤
if/else標籤
{% if condition1 %}
... display 1
{% elif condition2 %}
... display 2
{% else %}
... display 3
{% endif %}
#根據條件判斷是否輸出。if/else 支援巢狀。
#{% if %} 標籤接受 and , or 或者 not 關鍵字來對多個變數做判斷 ,或者對變數取反( not )。
for標籤
{% for %} 允許我們在一個序列上迭代。
與Python的 for 語句的情形類似,迴圈語法是 for X in Y ,Y是要迭代的序列而X是在每一個特定的迴圈中使用的變數名稱。
每一次迴圈中,模板系統會渲染在 {% for %} 和 {% endfor %} 之間的所有內容。
#例如,給定一個運動員列表 university_list 變數,我們可以使用下面的程式碼來顯示這個列表
<ul>
{% for university in university_list %}
<li>{{ university}}</li>
{% endfor %}
</ul>
#給標籤增加一個reversed使得列表被反向迭代
<ul>
{%for university in university_list reversed%}
<li>{{university}}</li>
{%end for%}
</ul>
#可以巢狀使用 {% for %} 標籤
#view.py
from django.shortcuts import render
def hello(request):
context = {}
context['university_list'] = [{'name':'ECUST','subjects':['Chemistry','biography']},{'name':'Princeton','subjects':['CS','EE']},{'name':'CMU','subjects':['CS','AI']}]
return render(request,'hello.html',context)
#hello.html
{%for university in university_list%}
<h1>{{university.name}}</h1>
<ul>
{%for subject in university.subjects%}
<li>{{subject}}</li>
{%endfor%}
</ul>
{%endfor%}
ifequal/ifnotequal 標籤
{% ifequal %} 標籤比較兩個值,當他們相等時,顯示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。
下面的例子比較兩個模板變數 user 和 currentuser :
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}
和 {% if %} 類似, {% ifequal %} 支援可選的 {% else%} 標籤:8
{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% else %}
<h1>No News Here</h1>
{% endifequal %}
註釋標籤
Django 註釋使用 {# #}。
{# 這是一個註釋 #}
過濾器
模板過濾器可以在變數被顯示前修改它,過濾器使用管道字元,如下所示:
{{ name|lower }} {{ name }} 變數被過濾器 lower 處理後,文件大寫轉換文字為小寫。
過濾管道可以被* 套接* ,既是說,一個過濾器管道的輸出又可以作為下一個管道的輸入:
{{ my_list|first|upper }} 以上例項將第一個元素並將其轉化為大寫。
有些過濾器有引數。 過濾器的引數跟隨冒號之後並且總是以雙引號包含。 例如:
{{ bio|truncatewords:“30” }}
這個將顯示變數 bio 的前30個詞。
#hello.html
<h1>{{bio|truncatewords:'2'}}</h1>
<h1>{{bio|first|upper}}</h1>
#view.py
from django.shortcuts import render
def hello(request):
context = {}
context['bio'] = 'xuhuan is handsome'
return render(request,'hello.html',context)
其他過濾器:
addslashes : 新增反斜槓到任何反斜槓、單引號或者雙引號前面。
date : 按指定的格式字串引數格式化 date 或者 datetime 物件,例項:
{{ pub_date|date:“F j, Y” }}
length : 返回變數的長度。
include 標籤
{% include %} 標籤允許在模板中包含其它的模板的內容。
下面這個例子都包含了 nav.html 模板:
{% include “nav.html” %}
模板繼承
模板可以用繼承的方式來實現複用。
# base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>EAST CHINA UNIVERSITY OF SCIENCE AND TECHNOLOGY</title>
</head>
<body>
<h1>ECUST</h1>
<p>Hello Shanghai~</p>
{% block mainbody %}
<p>original</p>
{% endblock %}
</body>
</html>
#以上程式碼中,名為 mainbody 的 block 標籤是可以被繼承者們替換掉的部分。所有的 {% block %} 標籤告訴模板引擎,子模板可以過載這些部分。
#hello.html
{%extends "base.html" %}
{% block mainbody %}
<p>hello ECUST~</p>
{% endblock %}
#第一行程式碼說明 hello.html 繼承了 base.html 檔案。可以看到,這裡相同名字的 block 標籤用以替換 base.html 的相應 block。