黑松山资源网 Design By www.paidiu.com
打开current_datetime 视图。 以下是其内容:
from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
让我们用 Django 模板系统来修改该视图。 第一步,你可能已经想到了要做下面这样的修改:
from django.template import Template, Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() t = Template("<html><body>It is now {{ current_date }}.</body></html>") html = t.render(Context({'current_date': now})) return HttpResponse(html)
没错,它确实使用了模板系统,但是并没有解决我们在本章开头所指出的问题。 也就是说,模板仍然嵌入在Python代码里,并未真正的实现数据与表现的分离。 让我们将模板置于一个 单独的文件 中,并且让视图加载该文件来解决此问题。
你可能首先考虑把模板保存在文件系统的某个位置并用 Python 内建的文件操作函数来读取文件内容。 假设文件保存在 /home/djangouser/templates/mytemplate.html 中的话,代码就会像下面这样:
from django.template import Template, Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() # Simple way of using templates from the filesystem. # This is BAD because it doesn't account for missing files! fp = open('/home/djangouser/templates/mytemplate.html') t = Template(fp.read()) fp.close() html = t.render(Context({'current_date': now})) return HttpResponse(html)
然而,基于以下几个原因,该方法还算不上简洁:
- 它没有对文件丢失的情况做出处理。 如果文件 mytemplate.html 不存在或者不可读, open() 函数调用将会引发 IOError 异常。
- 这里对模板文件的位置进行了硬编码。 如果你在每个视图函数都用该技术,就要不断复制这些模板的位置。 更不用说还要带来大量的输入工作!
- 它包含了大量令人生厌的重复代码。 与其在每次加载模板时都调用 open() 、 fp.read() 和 fp.close() ,还不如做出更佳选择。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 纳塔含成就每日委托——「小小人儿,快长大」
- 李家明.1992-不老的情人【新艺宝】【WAV+CUE】
- 以莉·高露.2015-美好時刻【风潮】【FLAC分轨】
- 谢金晶.2017-放心【豪记】【WAV+CUE】
- 炉石传说最强死亡骑士卡组是什么 死亡骑士最强天梯卡组推荐一览
- 炉石传说最强德鲁伊卡组是哪个 德鲁伊最强天梯卡组推荐一览
- 炉石传说最强战士卡组是哪个 战士最强天梯卡组推荐一览
- LexVandyke《HistoriadeunAmor情陷地中海》[WAV+CUE]
- TheBestPopClassics《LIGHTRHYTHMSOUND2》[WAV+CUE]
- TheLatinSoundofLexVandyke-ConciertodeAranjuez拉丁情人2012[SACD-ISO]
- 《怪物猎人世界》史低¥44,《耻辱终极版》仅需¥12
- 杉果秋促最后一天!海量3A大作击穿Steam史低
- 【果娘聊天室】国庆假期就这么水灵灵地结束啦!
- 《死或生》恋爱游戏新角色:来自大雷温柔公主的喂食
- 《寂静岭2》原制作人盛赞《寂静岭2:重制版》:新玩家能玩 我超高兴