做爲web框架,Django提供了模板,用於編寫html代碼,模板的設計實現了業務邏輯view與現實內容template的解耦。模板包含兩部分:css
settings.py中DIRS
定義一個目錄列表,模板引擎按列表順序搜索目錄以查找模板文件,一般是在項目的根目錄下建立templates
目錄html
模板文件: book/index.htmlweb
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試項目邏輯</title> </head> <body> <h1>{{ test }}</h1> </body> </html>
視圖渲染模板django
from django.shortcuts import render from django.views.generic import View class IndexView(View): def get(self, request): context = {'test': '測試項目邏輯'} return render(request, 'book/index.html', context)
路由url配置瀏覽器
# book.url from django.conf.urls import url from .views import IndexView urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), ] #demo.url urlpatterns = [ ... url(r'^book/', include('book.urls', namespace='book')), ]
瀏覽器訪問http://127.0.0.1/book框架
視圖,傳入參數ide
from django.shortcuts import render
from django.views.generic import View
from .models import Book
class IndexView(View):
def get(self, request):
book = Book.objects.get(id=1)
context = {'username': '何波安', 'age': 18, 'book': book}
return render(request, 'book/index.html',context)
模板文件index.html:使用{{ 變量名 }}的方式引用, 若是變量不存在,則取出空字符串函數
<body> 姓名: {{ username }} <br/> 年齡: {{ age }} <br/> 圖書: {{ book.title }} </body>
1)for 循環標籤oop
{% for item in 列表 %}
執行循環邏輯
{{ forloop.counter }}獲取當前是第幾回循環,從1開始
{% empty %}
列表爲空或不存在時執行此邏輯
{% endfor %}
class IndexView(View):
def get(self, request):
books = Book.objects.all()
context = {'booklist': books}
return render(request, 'book/index.html',context)
<body> <ul> {% for book in booklist %} <span style="color: red"> {{ forloop.counter }}</span> -{{ book.title }}<br /> {% endfor %} </ul> </body>
2)if標籤測試
{% if ... %}
邏輯1
{% elif ... %}
邏輯2
{% else %}
邏輯3
{% endif %}
<ul> {% for book in booklist %} {% if book.id <= 2 %} <li style="background: red">{{ book.title }}</li> {% elif book.id == 3 %} <li style="background: green">{{ book.title }}</li> {% else %} <li style="background: blue">{{ book.title }}</li> {% endif %} {% endfor %} </ul> </body>
過濾器是經過管道"|"進行使用的,例如{{ name | length }},將返回name的長度。過濾器至關於一個函數,把當前變量傳入過濾器中,而後過濾器根據本身的功能,再返回相應的值,最後再將結果渲染到頁面中。
經常使用的過濾器
變量|length
變量|default:默認值
date,用於對日期類型的值進行字符串格式化
日期|date:'Y年m月j日 H時i分s秒'
過濾器演練
場景: 當用戶沒有自定義個性簽名的時候,使用default傳遞值,以下:
class IndexView(View): def get(self, request): context = {'signature': '世界真的好贊'} return render(request, 'book/index.html',context)
index.html
個性簽名: {{ signature| default:'這我的真懶,什麼都沒有留下~' }}
當沒有定義signature,則會顯示"這我的真懶,什麼都沒有留下~"
class IndexView(View): def get(self, request): context = { #'signature': '世界真的好贊' } return render(request, 'book/index.html',context)
模板繼和類的繼承含義是同樣的,主要是爲了提升代碼重用,減輕開發人員的工做量,典型應用:
父模板
templates
文件目錄下block標籤
:用於在父模板中預留區域,留給子模板填充差別性的內容{% block 名稱 %}
預留區域,能夠編寫默認內容,也能夠沒有默認內容
{% endblock 名稱 %}
子模板
templates/應用
文件目錄下extends標籤
:繼承,寫在子模板文件的第一行
子模版不用填充父模版中的全部預留區域,若是子模版沒有填充,則使用父模版定義的默認值
{% block 名稱 %}
實際填充內容
{{ block.super }} 用於獲取父模板中block的內容,也能夠不獲取
{% endblock 名稱 %}
模板繼承演練
定義父子模板文件目錄