使用环境同前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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。