如何使用模板系统
想要在Python代码中使用模板系统,只需遵循下面两个步骤:
1.可以用原始的模板代码字符串创建一个 Template 对象,Django同样支持用指定模板文件路径的方式来创建 Template 对象;
调用 Template 对象的 render() 方法并提供给他变量(i.e., 内容).它将返回一个完整的模板字符串内容,包含了所有标签块与变量解析后的内容.
模板渲染
一旦你创建一个 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) 'My name is Stephane.'同一模板,多个上下文
一旦有了 模板 对象,你就可以通过它渲染多个背景(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, Pat1无论何时像这样使用同一模板源渲染多个背景,只创建 一次 模板 对象,然后对它多次调用 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}))
在到目前为止的例子中,我们通过 context 传递的简单参数值主要是字符串,还有一个 datetime.date 范例。然而,模板系统能够非常简洁地处理更加复杂的数据结构,例如list、dictionary和自定义的对象。
from django.template import Template, Context >>> person = {'name': 'Sally', 'age': '43'} >>> t = Template('{{ person.name }} is {{ person.age }} years old.') >>> c = Context({'person': person}) >>> t.render(c) 'Sally is 43 years old.'同样,也可以通过句点来访问对象的属性。比方说, Python 的 datetime.date 对象有 year 、 month 和 day 几个属性,你同样可以在模板中使用句点来访问这些属性:
from django.template import Template, Context >>> import datetime >>> d = datetime.date(1993, 5, 2) >>> d.year 1993 >>> d.month 5 >>> d.day 2 >>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.') >>> c = Context({'date': d}) >>> t.render(c) 'The month is 5 and the year is 1993.'用类的实例渲染模板
from django.template import Template, Context >>> class Person(object): ... def __init__(self, first_name, last_name): ... self.first_name, self.last_name = first_name, last_name >>> t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.') >>> c = Context({'person': Person('John', 'Smith')}) >>> t.render(c) 'Hello, John Smith.'最后,句点也可用于访问列表索引,
from django.template import Template, Context >>> t = Template('Item 2 is {{ items.2 }}.') >>> c = Context({'items': ['apples', 'bananas', 'carrots']}) >>> t.render(c) 'Item 2 is carrots.'方法调用行为
方法调用比其他类型的查找略为复杂一点。 以下是一些注意事项:
在方法查找过程中,如果某方法抛出一个异常,除非该异常有一个 silent_variable_failure 属性并且值为 True ,否则的话它将被传播。如果异常被传播,模板里的指定变量会被置为空字符串,比如:
仅在方法无需传入参数时,其调用才有效。 否则,系统将会转移到下一个查找类型(列表索引查找)。