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

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

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

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

关于python - 如何检查 python mako 模板中是否存在列表变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594753/

相关文章:

python - 如何使用 python 中的正则表达式删除括号内的文本?

python - 重复输入错误Django

python - 如何避免 mako %def 中的重复过滤器规范?

python - 来自未在 python 中使用 mako 呈现的变量的 Html 字符串

python - 在 OS X 上运行的 Python 中读取/写入另一个进程内存

python - 如何获取字典以及如何从 i for i in m if m 迭代中打破

python - python中的 growl 通知

python - Unicode解码错误: 'ascii' codec can't decode byte 0xc5

python - 如何检查mako模板中的instanceof?