使用環境同上篇django文章。html
運行django服務:
python
]# cd py3/django-test1/test4 ]# python manage.py runserver 192.168.255.70:8000
建立html模板文件:django
]# cd py3/django-test1/test4/templates/bookshop/ ]# vim base.html <!DOCTYPE html> <html> <head> <title>Title</title> {% block head %}{% endblock %} </head> <body> <h1>logo</h1> <hr> {% block content1 %} <h1>父模板--繼承</h1> {% endblock %} <hr> <h1>contact</h1> </body> </html>
base.html爲模板基礎,讓index2.html繼承base.html:vim
]# vim index2.html {% extends 'bookshop/base.html' %}
編輯視圖函數:瀏覽器
]# cd /root/py3/django-test1/test4 ]# vim bookshop/views.py from django.shortcuts import render from .models import * ... def index2(request): return render(request,'bookshop/index2.html')
添加應用url路由:bash
]# vim bookshop/urls.py from django.conf.urls import url from . import views urlpatterns = [ ... url(r'^index2$',views.index2, name='index2'), ]
瀏覽器訪問:http://192.168.255.70:8000/index2 ide
以上就是基本實現模板繼承的示例演示。函數
再修改index2.html:
this
]# vim templates/bookshop/index2.html {% extends 'bookshop/base.html' %} {% block content1 %} <h1>this is a index2.html page!</h1> {% endblock content1 %}
說明:url
block content1與父模板重名,則會覆蓋繼承的模板。
在結束標籤中{% endblock content1%}能夠添加名稱。