使用环境同前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
html>
Title{% block head %}{% endblock %}
{% block content1 %}
{% endblock %}
二级html模板:]# vim templates/bookshop/base_user.html
{% extends 'bookshop/base.html' %}
{% block content1 %}
用户导航 | {% block user_content %} {% endblock %} |
{% endblock content1 %}
三级html模板:
user1.html:]# vim templates/bookshop/user1.html
{% extends 'bookshop/base_user.html' %}
{% block head %}
{% endblock head %}
{% block user_content %}
{% endblock user_content %}
user2.html:]# vim templates/bookshop/user2.html
{% extends 'bookshop/base_user.html' %}
{% block user_content %}
{% 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'),
]
点击javascript的弹框,继续显示页面:
此例三层模板继承,说明,模板可以跨层级继承且可传递变量。