Skip to main content
 首页 » 编程设计

python之如何检查python mako模板中是否存在列表变量

2025年05月04日11sharpest

假设我的模板中有以下内容:

% 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'] 中的内容可用时。

我必须做什么?我不断收到:

IndexError: list index out of range 

与上述

请您参考如下方法:

PEP 8建议:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

所以你真的不需要检查长度,只需像这样检查它:

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