python的django框架中的context使用

一旦你创建一个 template 对象,你可以用 context 来传递数据给它。 一个context是一系列变量和它们值的集合。

context在django里表现为 context 类,在 django.template 模块里。 她的构造函数带有一个可选的参数: 一个字典映射变量和它们的值。 调用 template 对象 的 render() 方法并传递context来填充模板:

>>> 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对象,不是普通的python字符串。 你可以通过字符串前的u来区分。 在框架中,django会一直使用unicode对象而不是普通的字符串。 如果你明白这样做给你带来了多大便利的话,尽可能地感激django在幕后有条不紊地为你所做这这么多工作吧。 如果不明白你从中获益了什么,别担心。你只需要知道django对unicode的支持,将让你的应用程序轻松地处理各式各样的字符集,而不仅仅是基本的a-z英文字符。

字典和contexts

python的字典数据类型就是关键字和它们值的一个映射。 context 和字典很类似, context 还提供更多的功能。

变量名必须由英文字符开始 (a-z或a-z)并可以包含数字字符、下划线和小数点。 (小数点在这里有特别的用途,稍后我们会讲到)变量是大小写敏感的。

下面是编写模板并渲染的示例:

>>> from django.template import template, context
>>> raw_template = “””

dear {{ person_name }},


thanks for placing an order from {{ company }}. it’s scheduled to
… ship on {{ ship_date|date:”f j, y” }}.


… {% if ordered_warranty %}

your warranty information will be included in the packaging.

… {% else %}

you didn’t order a warranty, so you’re on your own when
… the products inevitably stop working.

… {% endif %}

sincerely,{{ company }}

“””
>>> t = template(raw_template)
>>> import datetime
>>> c = context({‘person_name’: ‘john smith’,
… ‘company’: ‘outdoor equipment’,
… ‘ship_date’: datetime.date(2009, 4, 2),
… ‘ordered_warranty’: false})
>>> t.render(c)
u”

dear john smith,

\n\n

thanks for placing an order from outdoor
equipment. it’s scheduled to\nship on april 2, 2009.

\n\n\n

you
didn’t order a warranty, so you’re on your own when\nthe products
inevitably stop working.

\n\n\n

sincerely,outdoor equipment

让我们逐步来分析下这段代码:

首先我们导入 (import)类 template 和 context ,它们都在模块 django.template 里。

我们把模板原始文本保存到变量 raw_template 。注意到我们使用了三个引号来 标识这些文本,因为这样可以包含多行。

接下来,我们创建了一个模板对象 t ,把 raw_template 作为 template 类构造函数的参数。

我们从python的标准库导入 datetime 模块,以后我们将会使用它。

然后,我们创建一个 context 对象, c 。 context 构造的参数是python 字典数据类型。 在这里,我们指定参数 person_name 的值是 ‘john smith’ , 参数company 的值为 ‘outdoor equipment’ ,等等。

最后,我们在模板对象上调用 render() 方法,传递 context参数给它。 这是返回渲染后的模板的方法,它会替换模板变量为真实的值和执行块标签。

注意,warranty paragraph显示是因为 ordered_warranty 的值为 true . 注意时间的显示, april 2, 2009 , 它是按 ‘f j, y’ 格式显示的。

如果你是python初学者,你可能在想为什么输出里有回车换行的字符(‘\n’ )而不是 显示回车换行? 因为这是python交互解释器的缘故: 调用 t.render(c) 返回字符串, 解释器缺省显示这些字符串的 真实内容呈现 ,而不是打印这个变量的值。 要显示换行而不是 ‘\n’ ,使用 print 语句: print t.render(c) 。

这就是使用django模板系统的基本规则: 写模板,创建 template 对象,创建 context , 调用 render() 方法。

同一模板,多个上下文

一旦有了 模板 对象,你就可以通过它渲染多个context, 例如:

>>> 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

无论何时我们都可以像这样使用同一模板源渲染多个context,只进行 一次模板创建然后多次调用render()方法渲染会更为高效:

# bad
for name in (‘john’, ‘julie’, ‘pat’):
t = template(‘hello, {{ name }}’)
print t.render(context({‘name’: name}))
# good
t = template(‘hello, {{ name }}’)
for name in (‘john’, ‘julie’, ‘pat’):
print t.render(context({‘name’: name}))

django 模板解析非常快捷。 大部分的解析工作都是在后台通过对简短正则表达式一次性调用来完成。 这和基于 xml 的模板引擎形成鲜明对比,那些引擎承担了 xml 解析器的开销,且往往比 django 模板渲染引擎要慢上几个数量级。

发表评论