使用环境同上篇django文章。


运行django服务:

]#cdpy3/django-test1/test4]#pythonmanage.pyrunserver192.168.255.70:8000

创建html模板文件:

]#cdpy3/django-test1/test4/templates/bookshop/]#vimbase.html<!DOCTYPEhtml><html><head><title>Title</title>{%blockhead%}{%endblock%}</head><body><h2>logo</h2><hr>{%blockcontent1%}<h2>父模板--继承</h2>{%endblock%}<hr><h2>contact</h2></body></html>

base.html为模板基础,让index2.html继承base.html:

]#vimindex2.html{%extends'bookshop/base.html'%}

编辑视图函数:

]#cd/root/py3/django-test1/test4]#vimbookshop/views.pyfromdjango.shortcutsimportrenderfrom.modelsimport*...defindex2(request):returnrender(request,'bookshop/index2.html')

添加应用url路由:

]#vimbookshop/urls.pyfromdjango.conf.urlsimporturlfrom.importviewsurlpatterns=[...url(r'^index2$',views.index2,name='index2'),]

浏览器访问:http://192.168.255.70:8000/index2

以上就是基本实现模板继承的示例演示。

再修改index2.html:

]#vimtemplates/bookshop/index2.html{%extends'bookshop/base.html'%}{%blockcontent1%}<h2>thisisaindex2.htmlpage!</h2>{%endblockcontent1%}

说明:

block content1与父模板重名,则会覆盖继承的模板。

在结束标签中{% endblock content1%}可以添加名称。



访问浏览器:http://192.168.255.70:8000/index2