欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

django学习系列之模板系统篇(二)

程序员文章站 2022-09-10 12:36:06
这篇文章讲怎么在视图中使用模板。只会说没用,用起来才是真的。 这里必须提到一个新概念了:模板目录。在模板目录里面,你存放了一堆模板文件。 怎么让找到模板目录呢?靠设置文件。 在项目...

这篇文章讲怎么在视图中使用模板。只会说没用,用起来才是真的。

这里必须提到一个新概念了:模板目录。在模板目录里面,你存放了一堆模板文件。

怎么让找到模板目录呢?靠设置文件。

在项目中找到settings.py文件,找到template_dirs,在这一项里面添加你的模板目录位置。

linux系统下有两种添加方法:

1.使用绝对路径。比如:

template_dirs = (

'/home/django/mysite/templates', #结尾要有逗号

)

2.使用内部变量__file__,改变量被自动设置为代码所在的python模块文件名。比如:

template_dirs = (

os.path.join(os.path.dirname(__file__),'templates').replace(' \\','/'),

)

在settings.py所在目录下查找templates目录。


具体使用

先看一个例子。

fromdjango.template.loader import get_template

fromdjango.template import context

from django.httpimport httpresponse

import datetime


defcurrent_datetime(request):

now =datetime.datetime.now()

t =get_template('current_datetime.html')

html =t.render(context({'current_date': now}))

returnhttpresponse(html)

前面也用过这个例子,不解释了。这是一种用法,使用httpresponse()方法。

但是应答http请求的操作太常用了,django提供了一个快捷的方法,位于django.shortcuts模块中名为render_to_response()的方法。

使用render_to_response()方法,上面的代码可以简化为:

from django.httpimport render_to_response

import datetime


defcurrent_datetime(request):

now =datetime.datetime.now()

returnrender_to_response('current_datetime.html', {'current_date': now})

render_to_response()的第一个参数必须是要使用的模板名称。如果要给定第二个参数,那么该参数必须是为该模板创建context 时所使用的字典。如果不提供第二个参数,render_to_response()使用一个空字典。


写过web的人都知道html文档的内容实在多,要是能够重用,那就太好了。

重用的第一种方法是使用{%include %}标签,第二种方法就是模板继承。

下面重点将第二种方法,第一种方法参考标签的用法。

模板继承,从本质上来说就是先构造一个基础框架模板,而后在其子模板中对它所包含站点公用部分和定义块进行重载。跟类继承的概念差不多。


直接上示例:

假设一个文件base.html

{%block title %}{% endblock %}

myhelpful timestamp site

{% blockcontent %}{% endblock %}

{% blockfooter %}


thanksfor visiting my site.

{% endblock%}

="en">