Django框架下在视图中使用模版的方法

yipeiwu_com5年前Python基础

 打开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() ,还不如做出更佳选择。

相关文章

解决python字典对值(值为列表)赋值出现重复的问题

解决python字典对值(值为列表)赋值出现重复的问题

可能很少有人遇到这个问题,网上也没找到,这里记录一下,希望也可以帮到其他人。 问题描述:假设有一个字典data,其键不定,可能随时添加键(这不是关键),某一个键下面对应的值为一个长度为1...

老生常谈Python startswith()函数与endswith函数

函数:startswith() 作用:判断字符串是否以指定字符或子字符串开头 一、函数说明 语法:string.startswith(str, beg=0,end=len(string)...

基于Python实现的扫雷游戏实例代码

本文实例借鉴mvc模式,核心数据为model,维护1个矩阵,0表无雷,1表雷,-1表已经检测过。 本例使用python的tkinter做gui,由于没考虑可用性问题,因此UI比较难看,p...

python实现转圈打印矩阵

本文实例为大家分享了python实现转圈打印矩阵的具体代码,供大家参考,具体内容如下 #! conding:utf-8 __author__ = "hotpot" __date__...

Python魔法方法功能与用法简介

本文实例讲述了Python魔法方法功能与用法。分享给大家供大家参考,具体如下: 1、什么是魔法方法? 魔法方法就是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某...