简体   繁体   中英

How to check if list variable exists in python mako template?

Assuming I have the following in my template:

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

My issue is the above does not work as mydict['somekey'] is always an array, but it could be empty. I want to be able to check to make sure that if mydict['somekey'] is defined, I can add a check to make sure either 1) the list size is greater than 0 (from inside the template) or if the mydict['somekey'] has elements in it so that I can print out what is in mydict['somekey'][0]['hellothere'] when available.

What must I do? I keep getting an:

IndexError: list index out of range

with the above

PEP 8 recommends:

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

So really you don't need to check the length and just check it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM