Django 编写模板并渲染的示例

 1 >>> from django.template import Template, Context
 2 >>> raw_template = """<p>Dear {{ person_name }},</p>
 3 ...
 4 ... <p>Thanks for ordering {{ product }} from {{ company }}. It's scheduled
 5 ... to ship on {{ ship_date|date:"F j, Y" }}.</p>
 6 ...
 7 ... {% if ordered_warranty %}
 8 ... <p>Your warranty information will be included in the packaging.</p>
 9 ... {% endif %}
10 ...
11 ... <p>Sincerely,<br />{{ company }}</p>"""
12 >>> t = Template(raw_template)
13 >>> import datetime
14 >>> c = Context({'person_name': 'John Smith',
15 ...     'product': 'Super Lawn Mower',
16 ...     'company': 'Outdoor Equipment',
17 ...     'ship_date': datetime.date(2009, 4, 2),
18 ...     'ordered_warranty': True})
19 >>> t.render(c)
20 "<p>Dear John Smith,</p>

<p>Thanks for ordering Super Lawn Mower from
21 Outdoor Equipment. It's scheduled 
to ship on April 2, 2009.</p>



22 <p>Your warranty information will be included in the packaging.</p>



23 <p>Sincerely,<br />Outdoor Equipment</p>"

让我们逐句看看这段代码:

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

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

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

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

然后,我们创建一个 Context 对象, c 。 Context 构造的参数是Python 字典数据类型,在这里,我们给的参数是 person_name 值为 'John Smith' , product 值为 'Super Lawn Mower' ,等等。

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

注意,warranty paragraph显示是因为 ordered_warranty 的值为 True . 注意时间的显示, April 2, 2009 , 它是按 'F j, Y' 格式显示的。 (我们很快就会在 date 过滤器解释这些格式)

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

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

本人目前在学习python、前端、数据库和linux相关的内容,故打算写一些学习笔记,包括安装软件遇到的一些问题、编程语言的学习。 学习如逆水行舟,你在原地踏步的同时,别人一直在前进!
原文地址:https://www.cnblogs.com/souhaite/p/10752676.html