Django框架下在视图中使用模版的方法
打开current_datetime视图。以下是其内容:
fromdjango.httpimportHttpResponse importdatetime defcurrent_datetime(request): now=datetime.datetime.now() html="<html><body>Itisnow%s.</body></html>"%now returnHttpResponse(html)
让我们用Django模板系统来修改该视图。第一步,你可能已经想到了要做下面这样的修改:
fromdjango.templateimportTemplate,Context fromdjango.httpimportHttpResponse importdatetime defcurrent_datetime(request): now=datetime.datetime.now() t=Template("<html><body>Itisnow{{current_date}}.</body></html>") html=t.render(Context({'current_date':now})) returnHttpResponse(html)
没错,它确实使用了模板系统,但是并没有解决我们在本章开头所指出的问题。也就是说,模板仍然嵌入在Python代码里,并未真正的实现数据与表现的分离。让我们将模板置于一个单独的文件中,并且让视图加载该文件来解决此问题。
你可能首先考虑把模板保存在文件系统的某个位置并用Python内建的文件操作函数来读取文件内容。假设文件保存在/home/djangouser/templates/mytemplate.html中的话,代码就会像下面这样:
fromdjango.templateimportTemplate,Context fromdjango.httpimportHttpResponse importdatetime defcurrent_datetime(request): now=datetime.datetime.now() #Simplewayofusingtemplatesfromthefilesystem. #ThisisBADbecauseitdoesn'taccountformissingfiles! fp=open('/home/djangouser/templates/mytemplate.html') t=Template(fp.read()) fp.close() html=t.render(Context({'current_date':now})) returnHttpResponse(html)
然而,基于以下几个原因,该方法还算不上简洁:
- 它没有对文件丢失的情况做出处理。如果文件mytemplate.html不存在或者不可读,open()函数调用将会引发IOError异常。
- 这里对模板文件的位置进行了硬编码。如果你在每个视图函数都用该技术,就要不断复制这些模板的位置。更不用说还要带来大量的输入工作!
- 它包含了大量令人生厌的重复代码。与其在每次加载模板时都调用open()、fp.read()和fp.close(),还不如做出更佳选择。