在使用Django进行web开发时,往往会构造一个基础框架模板即base.html,而后在其子模板中对它所包含站点公用部分和定义块进行重载。
首先创建一个base.html,源码为:
{% block title %}{% endblock %}
?My helpful timestamp site
?{% block content %}{% endblock %}
?{% block footer %}
?
?Thanks for visiting my site.
?{% endblock%}
这个叫做base.html的模板定义了一个简单的html框架文档,等会我们将在我们的站点中的页面使用它。子模板的作用就是重载、添加或保留那些块的内容。
现在新建一个current_datetime.html模板来使用它:
{% extends "base.html" %}
{% block title %}The current time{% endblock %}
{% block content %}
It is now {{current_date }}.
{% endblock %}
再新建一个hours_ahead.html模板,源码为:
{% extends "base.html" %}
{% block title %}Future time{% endblock %}
{% block content %}
In {{hour_offset }} hour(s),it will be {{next_time}}.
{% endblock? %}
上面的部分非html标签等会再来解释它,现在在views.py中新建两个函数,index4,与index5,分别对应这两个模板。源码为:
def index4(req,offset):
? ? offset=int(offset)
? ? next_time=datetime.datetime.now()+datetime.timedelta(hours=offset)
? ? return render_to_response("hours_ahead.html",{'hour_offset':offset,'next_time':next_time})
def index5(req):
? ? now=datetime.datetime.now()
? ? return render_to_response('current_datetime.html',{'current_date':now})
在url中的配置为:
?url(r'^hours_ahead/(\d{1,2}$)','blog.views.index4'),
? ? url(r'^current_datetime/$','blog.views.index5'),
现在启动服务器,在浏览器中查看效果,current_datetime.html为:

hours_ahead.html中的效果为:

如此两个html效果就显示出来了,同时也解释一下base.html中所起的作用,两个html中都使用了{% extends? %}标记,这个就是继承base.html中的内容,在使用{ % block XXXXX %}? ? {% endblock%}时,中间的内容便是插入在使用了base.html两个标签的中间,由此便极大的避免了代码的冗余。每个模板只包含自己独一无二的代码,无需多余的部分,而如果想要进行站点级的设计修改,仅需修改base.html,所有其他模板会立即反映出所做修改。
上述,便是django之继承使用base.html模板。