2016-06-28 80 views
1

假設我在我的Django模板以下:Do Django模板實現邏輯表達式的短路嗎?

{% if a != None and a.b > 5 %} 

我可以肯定,如果a是無a.b > 5不會進行評估?

IE:python的短路,而評估邏輯表達式踢在Django模板?

+1

試試吧?這應該需要兩秒鐘的時間來測試。 –

+1

他們做短路。 –

回答

1

此行爲不會出現在正式文件中指定,但bug #13373存在意味着他們這樣做,除了在V1.2測試版。

commit fef0d25bdc中所做的修復似乎仍然存在於smartif.pycurrent version中,所以假設它仍然有效是相當安全的。

2

是的,它會短路。我瀏覽了Django 1.9.2的源代碼,並認爲我發現了the relevant code

# Operator precedence follows Python. 
# NB - we can get slightly more accurate syntax error messages by not using the 
# same object for '==' and '='. 
# We defer variable evaluation to the lambda to ensure that terms are 
# lazily evaluated using Python's boolean parsing logic. 
OPERATORS = { 
    'or': infix(6, lambda context, x, y: x.eval(context) or y.eval(context)), 
    'and': infix(7, lambda context, x, y: x.eval(context) and y.eval(context)), 
    'not': prefix(8, lambda context, x: not x.eval(context)), 
    'in': infix(9, lambda context, x, y: x.eval(context) in y.eval(context)), 
    'not in': infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)), 
    # This should be removed in Django 1.10: 
    '=': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), 
    '==': infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), 
    '!=': infix(10, lambda context, x, y: x.eval(context) != y.eval(context)), 
    '>': infix(10, lambda context, x, y: x.eval(context) > y.eval(context)), 
    '>=': infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)), 
    '<': infix(10, lambda context, x, y: x.eval(context) < y.eval(context)), 
    '<=': infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)), 
} 

IfParser類用於評估在if塊表達的條件。以上,它被看作使用內置的and功能。

一個例子證明這可以使用像的視圖:

def printer(): print 'called' 

class IndexView(TemplateView): 
    template_name = 'index.html' 
    def get(self, request, *args, **kwargs): 
     return self.render_to_response({'log': printer}) 

以下模板將並不會分別打印「被稱爲」到控制檯。

{% if True and log %} # prints "called" 
{% if False and log %} # does not print "called"