方法調(diào)用行為
方法調(diào)用比其他類型的查找略為復(fù)雜一點(diǎn)。 以下是一些注意事項(xiàng):
??? 在方法查找過(guò)程中,如果某方法拋出一個(gè)異常,除非該異常有一個(gè) silent_variable_failure 屬性并且值為 True ,否則的話它將被傳播。如果異常被傳播,模板里的指定變量會(huì)被置為空字符串,比如:
>>> 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 .'
??? 僅在方法無(wú)需傳入?yún)?shù)時(shí),其調(diào)用才有效。 否則,系統(tǒng)將會(huì)轉(zhuǎn)移到下一個(gè)查找類型(列表索引查找)。
??? 顯然,有些方法是有副作用的,好的情況下允許模板系統(tǒng)訪問(wèn)它們可能只是干件蠢事,壞的情況下甚至?xí)l(fā)安全漏洞。
??? 例如,你的一個(gè) BankAccount 對(duì)象有一個(gè) delete() 方法。 如果某個(gè)模板中包含了像 {{ account.delete }}這樣的標(biāo)簽,其中`` account`` 又是BankAccount 的一個(gè)實(shí)例,請(qǐng)注意在這個(gè)模板載入時(shí),account對(duì)象將被刪除。
??? 要防止這樣的事情發(fā)生,必須設(shè)置該方法的 alters_data 函數(shù)屬性:
def delete(self): # Delete the account delete.alters_data = True
??? 模板系統(tǒng)不會(huì)執(zhí)行任何以該方式進(jìn)行標(biāo)記的方法。 接上面的例子,如果模板文件里包含了 {{ account.delete }} ,對(duì)象又具有 delete()方法,而且delete() 有alters_data=True這個(gè)屬性,那么在模板載入時(shí), delete()方法將不會(huì)被執(zhí)行。 它將靜靜地錯(cuò)誤退出。
如何處理無(wú)效變量
默認(rèn)情況下,如果一個(gè)變量不存在,模板系統(tǒng)會(huì)把它展示為空字符串,不做任何事情來(lái)表示失敗。 例如:
>>> 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ā)一個(gè)異常,因?yàn)檫@通常是人為錯(cuò)誤造成的。 這種情況下,因?yàn)樽兞棵绣e(cuò)誤的狀況或名稱, 所有的查詢都會(huì)失敗。 現(xiàn)實(shí)世界中,對(duì)于一個(gè)web站點(diǎn)來(lái)說(shuō),如果僅僅因?yàn)橐粋€(gè)小的模板語(yǔ)法錯(cuò)誤而造成無(wú)法訪問(wèn),這是不可接受的。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
