全部博文(73)
分类: Python/Ruby
2010-07-05 22:17:27
# 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}))
>>> from django.template import Context, Template
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template("My name is {{ name }}.")
>>> c = Context({"name": "Stephane"})
>>> t.render(c)
'My name is Stephane.'
>>> raw_template = """Dear {{ person_name }},
...
...Thanks for ordering {{ product }} 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.
... {% endif %}
...
...Sincerely,
"""
{{ company }}
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name':'John Smith',
'product':'Super Lawn Mower',
'company':'Outdoor Equipment',
'ship_date':datetime.date(2009,4,2),
'ordered_warranty':True})
>>> t.render(c)
u"Dear John Smith,
\n...\n...Thanks for ordering Super Lawn Mower from
\n...\n... \n...
Outdoor Equipment. It's scheduled\n... to ship on April 2, 2009.Your warranty information will be included in the packaging.
\n... \n...\n...Sincerely,
"
Outdoor Equipment
在 Django 模板中遍历复杂数据结构的关键是句点字符 (.)。
使用句点可以访问字典的键值、属性、索引和对象的方法。
>>> people={'name':'Sally','age':'43'}
>>> t = Template('{{person.name}} is {{person.age}} years old')
>>> c = Context({'person':people})
>>> t.render(c)
u'Sally is 43 years old'
---------------------------------------------------------------------------------------------
>>> 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.'
例如,每个 Python 字符串都有 upper() 和 isdigit() 方法,你在模板中可以使用同样的句点语法来调用它们:
>>> from django.template import Template, Context
>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')
>>> t.render(Context({'var': 'hello'}))
'hello -- HELLO -- False'
>>> t.render(Context({'var': '123'}))
'123 -- 123 -- True'
最后,句点也可用于访问列表索引,例如:
>>> 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.'