上下文(context)物件
Context可以通過一個完全填充(full populated)的字典來初始化,也可以使用標準的Python字典語法向其新增刪除條目。
In [34]: c = Context({"foo":"bar"})
In [35]: c['foo']
Out[35]: 'bar'
In [36]: del c['foo'] // 刪除條目
In [37]: c['foo']
In [35]: c['foo']
Out[35]: 'bar'
In [36]: del c['foo'] // 刪除條目
In [37]: c['foo']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/home/abeen/django_test/mysite/<ipython console> in <module>()
/usr/local/lib/python2.6/dist-packages/Django-1.2.1-py2.6.egg/django/template/context.pyc in __getitem__ (self, key)
44 if key in d:
45 return d[key]
---> 46 raise KeyError(key)
47
48 def __delitem__(self, key):
KeyError: 'foo'
程式碼
In [38]: c['name'] = 'ABeen' //新加條目
In [39]: c['name']
Out[39]: 'ABeen'
In [40]: t = Template('my name is {{person.name}}')
In [41]: c = Context({'person': c})
In [42]: t.render(c)
Out[42]: u'my name is ABeen'
In [39]: c['name']
Out[39]: 'ABeen'
In [40]: t = Template('my name is {{person.name}}')
In [41]: c = Context({'person': c})
In [42]: t.render(c)
Out[42]: u'my name is ABeen'