2012-11-27 41 views
2

假設我已經在我的模板如下:如何檢查列表變量是否存在於python mako模板中?

% if not mydict['somekey'] is UNDEFINED: 
    ${mydict['somekey'][0]['hellothere']}</td></tr> 
% endif  

我的問題是上面不作爲mydict['somekey']工作始終是一個數組,但它可能是空的。我希望能夠檢查以確保如果mydict['somekey']已定義,我可以添加一個檢查以確保1)列表大小大於0(來自模板內部),或者mydict['somekey']中包含元素,以便我可以在可用時打印出mydict['somekey'][0]['hellothere']中的內容。

我該做什麼?我不斷收到:上述

回答

1

PEP 8

IndexError: list index out of range 

建議:

對於序列(字符串,列表,元組),使用的事實,空 序列都是假的。

所以真的不需要檢查長度,只是檢查它像這樣:

% if mydict.get('somekey'): 
    ${mydict['somekey'][0]['hellothere']}</td></tr> 
% endif 
相關問題