Django——如何使用Template以及如何向template传递变量
如何使用模板系统
在Python代码中使用Django模板的最基本方式如下:
-
Template 对象;
-
调用模板对象的render方法,并且传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。
——————————————————————————————基本方法————————————————————————————————————
创建模板对象
django.template 模块中,构造函数接受一个参数,原始模板代码。 让我们深入挖掘一下 Python的解释器看看它是怎么工作的。
当你创建一个 Template 对象,模板系统在内部编译这个模板到内部格式,并做优化,做好 渲染的准备。 如果你的模板语法有错误,那么在调用 Template() 时就会抛出 TemplateSyntaxError 异常。
模板渲染
Template 对象,你可以用 context 来传递数据给它。 一个context是一系列变量和它们值的集合。
render() 方法并传递context来填充模板。
/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)
然而,基于以下几个原因,该方法还算不上简洁:
-
IOError 异常。
-
这里对模板文件的位置进行了硬编码。 如果你在每个视图函数都用该技术,就要不断复制这些模板的位置。 更不用说还要带来大量的输入工作!
-
fp.close() ,还不如做出更佳选择。
为了解决这些问题,我们采用了 模板自加载 跟 模板目录 的技巧.
——————————————————————————————合理方法————————————————————————————
模板自加载
为了减少模板加载调用过程及模板本身的冗余代码,Django 提供了一种使用方便且功能强大的 API ,用于从磁盘中加载模板,
settings.py。
TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. )
TEMPLATE_DIRS 中:
TEMPLATE_DIRS 的内容,如: 例如:
import os.path TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), 'templates').replace('\','/'), )
templates 进行连接。如果在windows下,它会智能地选择正确的后向斜杠”“进行连接,而不是前向斜杠”/”。
TEMPLATE_DIRS 设置后,下一步就是修改视图代码。
让它使用 Django 模板加载功能而不是对模板路径硬编码。 返回 current_datetime 视图,进行如下修改:
from django.template.loader import get_template from django.template import Context from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() t = get_template('current_datetime.html') html = t.render(Context({'current_date': now})) return HttpResponse(html)
Template 对象。
.html后缀没有直接的联系。 你可以选择任意后缀的任意文件,只要是符合逻辑的都行。甚至选择没有后缀的文件也不会有问题。
该页面与我们在第三章解释过的错误页面相似,只不过多了一块调试信息区: 模板加载器事后检查区。 该区域显示 Django 要加载哪个模板、每次尝试出错的原因(如:文件不存在等)。 当你尝试调试模板加载错误时,这些信息会非常有帮助。
current_datetime.html 文件:
<html><body>It is now {{ current_date }}.</body></html>
在网页浏览器中刷新该页,你将会看到完整解析后的页面。
——————————————————————————其他方法————————————————————————————————————
render_to_response()
HttpResponse返回。
render_to_response() 的函数。大多数情况下,你会使用,除非你的老板以代码行数来衡量你的工作。
—————————————————————context处理器的用处原来是为了简化模板渲染——————————————————————
processors 的麻烦。
TEMPLATE_CONTEXT_PROCESSORS 设置如下:
TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', )