您好,登錄后才能下訂單哦!
使用環境同前django文章。
啟動django的web服務:
]# cd /root/py3/django-test1/test4 ]# python manage.py runserver 192.168.255.70:8000
一級html模板為base.html;
二級html模板為base_user.html,bae_user.html繼承自base.html;
三級html模板為user1.html和user2.html都繼承自base_user.html。
分別編寫html模板文件:
一級html模板:
]# cd /root/py3/django-test1/test4/ ]# vim templates/bookshop/base.html <!DOCTYPE html> <html> <head> <title>Title</title> {% block head %}{% endblock %} </head> <body> <h2>logo</h2> <hr> {% block content1 %} <h2>父模板--繼承</h2> {% endblock %} <hr> <h2>contact</h2> </body> </html>
二級html模板:
]# vim templates/bookshop/base_user.html {% extends 'bookshop/base.html' %} {% block content1 %} <table border="1"> <tr> <td height="300">用戶導航</td> <td>{% block user_content %} {% endblock %}</td> </tr> </table> {% endblock content1 %}
三級html模板:
user1.html:
]# vim templates/bookshop/user1.html {% extends 'bookshop/base_user.html' %} {% block head %} <script>alert('hello python-django')</script> {% endblock head %} {% block user_content %} <h2>用戶中心1</h2> {% endblock user_content %}
user2.html:
]# vim templates/bookshop/user2.html {% extends 'bookshop/base_user.html' %} {% block user_content %} <h2>用戶中心2</h2> {% endblock user_content %}
注意:要想在頁面顯示內容,就必須寫在{%block%}標簽內,才有效,其它地方都不會顯示在頁面上。
編寫視圖函數:
]# vim bookshop/views.py from django.shortcuts import render from .models import * ... def index(request): #list = HeroInfo.objects.all() list = HeroInfo.objects.filter(isDelete=False) context = {'list1':list} return render(request,'bookshop/index.html',context) def show(request,id): context = {'id':id} return render(request,'bookshop/show.html',context) def index2(request): return render(request,'bookshop/index2.html') def user1(request): context = {'username':'python-django'} return render(request, 'bookshop/user1.html', context) def user2(request): return render(request,'bookshop/user2.html')
配置應用的url路由:
]# vim bookshop/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(\d+)$', views.show, name='show'), url(r'^(\d+)/(\d+)$', views.show, name='show'), url(r'^index2$', views.index2, name='index2'), url(r'^user1', views.user1, name='user1'), url(r'^user2', views.user2, name='user2'), ]
瀏覽器訪問:http://192.168.255.70:8000/user1
點擊javascript的彈框,繼續顯示頁面:
訪問瀏覽器:http://192.168.255.70:8000/user2
此例三層模板繼承,說明,模板可以跨層級繼承且可傳遞變量。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。