>>> from django import template
>>> t = template.Template('My name is {{ name }}.')
>>> c = template.Context({'name': 'Haozi'})
>>> print t.render(c)
My name is Haozi.
>>> c = template.Context({'name': 'Wuch'})
>>> print t.render(c)
My name is Wuch. 4.1.1. 创建模板对象
创建一个 Template 对象的方法就是直接实例化它。 Template 类就在 django.template 模块中,构造函数接受一个“原始模板代码”作为参数。
>>> from django.template import Context, Template
>>> t = Template('My name is {{ name }}.')
>>> c = Context({'name': 'Stephane'})
>>> t.render(c)
u'My name is Stephane.'
需要注意的是,t.render(c)返回值是一个Unicode对象,不是普通的字符串。 你可以通过字符串前的u来区分。 在Django框架中,会一直使用Unicode字符串对象而不是普通的字符串。
>>> from django.template import Template, Context
>>> t = Template('Hello, {{ name }}')
>>> print t.render(Context({'name': 'John'}))
Hello, John
>>> print t.render(Context({'name': 'Julie'}))
Hello, Julie
>>> print t.render(Context({'name': 'Pat'}))
Hello, Pat 4.2. 在视图中使用模板
现在我们使用模板技术来创建视图。 重新打开我们在前一章在 mysite.views 中创建的 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代码里。 下面我们在改进一下代码,将模板置于一个单独的文件中,并在视图中加载模板文件来最终解决表现与数据分开的问题。
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.
'C:\My Files\Python Projects\mysite\templates',
)
下面我们是使用Python 代码这一点来构建动态的TEMPLATE_DIRS路劲的内容,代码如下:
import os.path
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.
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)
同时,在模板目录中创建包括以下模板代码 current_datetime.html 文件:
<html><body>It is now {{ current_date }}.</body></html>
这样如下图,是模板直接在IE中浏览的效果。
注意:模板的目录结构,否则无法正常加载模板,mytime URL最后的访问效果如下图: