#1、 同一个模板,多个上下文(Context) ''' 比较糟糕的写法,应该讲创建的Template对象的工作放到for循环外面 for name in ('John','Mike','Mary'): t = Template('Hello,{{name}}') t.render(Context({'name':name})) 比较好的写法 t = Template('Hello,{{name}}') for name in ('John','Mike','Mary'): print(t.render(Context({'name':name}))) Hello,John Hello,Mike Hello,Mary ''' def multContext(request): html = '
url(r'^multContext/$',MyTemplate.multContext)
#2、向上下文传递字典和列表 ''' 字典 person = {'name':'Mary','age':40} t = Template('{{person.name}} is {{person.age}} years old.') c = Context({'person':person}) t.render(c) u'Mary is 40 years old.' 列表 person1 = ['Mike',38] t = Template('{{person.0}} is {{person.1}} years old.') c = Context({'person':person1}) t.render(c) u'Mike is 38 years old.' ''' ''' #3、向上下文传递对象
以下是在Console中进行的实验:
class Person(object):
def __init__ (self):
self.name = 'Bill'
def name(self):
return 'Mike'
t = Template('Hello,{{person.name}}')
c = Context({'person':Person()})
t.render(c)
u'Hello,Bill'
class Person(object):
def __init__ (self):
self.name = 'Bill'
def name(self):
return 'Mike'
t = Template('Hello,{{person.name.upper}}')
c = Context({'person':Person()})
t.render(c)
>>>u'Hello,BILL'
注意:查找顺序 {{person.name}} 1.person['name'] 2.person.name 属性名优秀于方法,如果属性和方法同名的话,是会优先访问属性 3.person.name() 4.person[name] '''