在使用Django进行web开发时,往往会构造一个基础框架模板即base.html,而后在其子模板中对它所包含站点公用部分和定义块进行重载。首先创建一个base.html,源码为:<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock%}
</body>
</html>这个叫做base.html的模板定义了一个简单的html框架文档,等会我们将在我们的站点中的页面使用它。子模板的作用就是重载、添加或保留那些块的内容。现在新建一个current_datetime.html模板来使用它:{% extends "base.html" %}
{% block title %}The current time{% endblock %}{% block content %}
<p>It is now {{current_date }}.</p>
{% endblock %}再新建一个hours_ahead.html模板,源码为:{% extends "base.html" %}
{% block title %}Future time{% endblock %}{% block content %}
<p>In {{hour_offset }} hour(s),it will be {{next_time}}.</p>
{% 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模板。Ubuntu Server 12.04 安装Nginx+uWSGI+Django环境 http://www.linuxidc.com/Linux/2012-05/60639.htmDjango+Nginx+uWSGI 部署 http://www.linuxidc.com/Linux/2013-02/79862.htmDjango实战教程 http://www.linuxidc.com/Linux/2013-09/90277.htmDjango Python MySQL Linux 开发环境搭建 http://www.linuxidc.com/Linux/2013-09/90638.htmDjango 的详细介绍:请点这里
Django 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-04/115662.htm