方法調(diào)用行為
方法調(diào)用比其他類型的查找略為復(fù)雜一點。 以下是一些注意事項:
??? 在方法查找過程中,如果某方法拋出一個異常,除非該異常有一個 silent_variable_failure 屬性并且值為 True ,否則的話它將被傳播。如果異常被傳播,模板里的指定變量會被置為空字符串,比如:
>>> t = Template("My name is {{ person.first_name }}.")
>>> class PersonClass3:
... def first_name(self):
... raise AssertionError, "foo"
>>> p = PersonClass3()
>>> t.render(Context({"person": p}))
Traceback (most recent call last):
...
AssertionError: foo
>>> class SilentAssertionError(AssertionError):
... silent_variable_failure = True
>>> class PersonClass4:
... def first_name(self):
... raise SilentAssertionError
>>> p = PersonClass4()
>>> t.render(Context({"person": p}))
u'My name is .'
??? 僅在方法無需傳入?yún)?shù)時,其調(diào)用才有效。 否則,系統(tǒng)將會轉(zhuǎn)移到下一個查找類型(列表索引查找)。
??? 顯然,有些方法是有副作用的,好的情況下允許模板系統(tǒng)訪問它們可能只是干件蠢事,壞的情況下甚至?xí)l(fā)安全漏洞。
??? 例如,你的一個 BankAccount 對象有一個 delete() 方法。 如果某個模板中包含了像 {{ account.delete }}這樣的標(biāo)簽,其中`` account`` 又是BankAccount 的一個實例,請注意在這個模板載入時,account對象將被刪除。
??? 要防止這樣的事情發(fā)生,必須設(shè)置該方法的 alters_data 函數(shù)屬性:
def delete(self):
# Delete the account
delete.alters_data = True
??? 模板系統(tǒng)不會執(zhí)行任何以該方式進(jìn)行標(biāo)記的方法。 接上面的例子,如果模板文件里包含了 {{ account.delete }} ,對象又具有 delete()方法,而且delete() 有alters_data=True這個屬性,那么在模板載入時, delete()方法將不會被執(zhí)行。 它將靜靜地錯誤退出。
如何處理無效變量
默認(rèn)情況下,如果一個變量不存在,模板系統(tǒng)會把它展示為空字符串,不做任何事情來表示失敗。 例如:
>>> from django.template import Template, Context
>>> t = Template('Your name is {{ name }}.')
>>> t.render(Context())
u'Your name is .'
>>> t.render(Context({'var': 'hello'}))
u'Your name is .'
>>> t.render(Context({'NAME': 'hello'}))
u'Your name is .'
>>> t.render(Context({'Name': 'hello'}))
u'Your name is .'
系統(tǒng)靜悄悄地表示失敗,而不是引發(fā)一個異常,因為這通常是人為錯誤造成的。 這種情況下,因為變量名有錯誤的狀況或名稱, 所有的查詢都會失敗。 現(xiàn)實世界中,對于一個web站點來說,如果僅僅因為一個小的模板語法錯誤而造成無法訪問,這是不可接受的。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

