使用环境同上篇django文章。
运行django服务:
]# cd py3/django-test1/test4 ]# python manage.py runserver 192.168.255.70:8000
创建html模板文件:
]# 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 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路由:
]# 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
以上就是基本实现模板继承的示例演示。
再修改index2.html:
]# vim templates/bookshop/index2.html
{% extends 'bookshop/base.html' %}
{% block content1 %}
<h1>this is a index2.html page!</h1>
{% endblock content1 %}
说明:
block content1与父模板重名,则会覆盖继承的模板。
在结束标签中{% endblock content1%}可以添加名称。
访问浏览器:http://192.168.255.70:8000/index2
转载于:https://blog.51cto.com/linsj/2327794