一、extends使用方法
首先extends也就是繼承,子類繼承父類的一些特性。在django模板中通過繼承可以減少重復代碼。
首先我們建立一個app,名字叫做hello。別忘了在settings.py中的INSTALLED_APPS注冊這個app。不注冊會出現hello目錄下的templates中的模板無法調用。
1.在根目錄下的templates創建base.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% endblock %} </body> </html>
這里的block就是繼承后要被替換的內容,其他的則與該模板相同
2.在hello這個app中繼承這個模板
在hello目錄下新建templates目錄,再在此目錄下新建hello目錄。hello目錄中新建hello.html。目錄結構就像這樣,理解一下django模板引用路徑的規則
hello.html內容如下
{% extends 'base.html' %}
{% block title %}{{ title }}{% endblock %}
{% block content %}{{ content }}{% endblock %}
首行代碼就是先繼承base.html,也就是有了除了block的剩下內容。后面兩個則是在為block填空,填入的內容是要傳入的參數。這里分別是title和content。這里可以看出模板語句是單個大括號加百分號,而模板變量是雙大括號,沒有百分號。
3.添加路由和方法
路由文件urls.py內容如下
from django.contrib import admin from django.urls import path from hello import views urlpatterns = [ path('hello/<str:title>/<str:content>/',views.hello), path('admin/', admin.site.urls), ]
注意在路徑中獲取參數的方法,str還可以換為int。我覺得這種傳參的方法比較簡單容易理解,看了還有正則表達式的傳參方法不是很直觀,以后有機會再仔細學。
hello app中的views.py
from django.shortcuts import render # Create your views here. def hello(request,title,content): context={'title':title,'content':content} return render(request,'hello/hello.html',context)
這里函數的形參名就是在路由中獲取的參數名。通過傳遞參數會render給hello.html這個模板,而hello.html這個模板又會繼承base.html這個父模板。
實現效果如下
4.總結extends
通過extends可以減少代碼重復。可以再增加header、footer等來包含共同的頭部和底部內容。其實我是先找到的include,但是include要么放在head中,可以減少重復引入css或js,要么放在body中當一個共同的導航條,或者底部內容。然而如果要在多處都include就不如直接用extends了。
二、include使用方法
這里我們在hello下新建hello2.html和hello3.html。
hello2.html內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello2</title> </head> <body> {% include 'hello/hello3.html' %} </body> </html>
hello3.html內容如下
<p> this is a p in hello3.html </p>
可以看出,hello2.html包含了hello3.html中的內容。這樣也達到了減少重復代碼的作用。再添加views中hello2方法
def hello2(request): return render(request,'hello/hello2.html')
以及urls中添加hello2
from django.contrib import admin from django.urls import path from hello import views urlpatterns = [ path('hello2/',views.hello2), path('hello/<str:title>/<str:content>/',views.hello), path('admin/', admin.site.urls), ]
實現效果如下
最近寫了一個校內二手書交易平台的demo,很粗糙,就是個練練手的實戰吧算是,歡迎來看看roadwide/campus_bookmarket