user2174050
user2174050

Reputation: 65

py:choose with list of strings

I'm trying to use a choose statement inside a loop, I need to populate a table in this way:

<tr py:for="i in range(0,25)">
     <py:choose my_list[i]='0'>
         <py:when my_list[i]='0'><td>NOT OK</td></py:when>
         <py:otherwise><td>OK</td></py:otherwise>
     </py:choose>
...
...
</tr>

I have an error on the line <py:choose...>:

TemplateSyntaxError: not well-formed (invalid token): line...

But I cannot understand well how to use the choose statement! If I think as C-like (and it seem to me more logical) I need to write only:

<tr py:for="i in range(0,25)">
     <py:choose my_list[i]>
         <py:when my_list[i]='0'><td>NOT OK</td></py:when>
         <py:otherwise><td>OK</td></py:otherwise>
     </py:choose>
...
...
</tr>

Can you help me? Oh, my_list is a list of string. Then, if the string is 0 then for me is NOT OK, everything else is OK.

Upvotes: 0

Views: 354

Answers (1)

VooDooNOFX
VooDooNOFX

Reputation: 4762

Within the py:choose, you're not access the Ith item of my_list. Instead, i is set equal to the int from range. I assume this is a contrived example, and you're trying to access the Ith value of my_list. In this case, you should just iterate over my_list instead of using range at all.

Here's an example using your current methodolgies. The error is within py:choose itself:

from genshi.template import MarkupTemplate
template_text = """
<html xmlns:py="http://genshi.edgewall.org/" >
    <tr py:for="index in range(0, 25)">
         <py:choose test="index">
             <py:when index="0"><td>${index} is NOT OK</td></py:when>
             <py:otherwise><td>${index} is OK</td></py:otherwise>
         </py:choose>
    </tr>
</html>
"""
tmpl = MarkupTemplate(template_text)
stream = tmpl.generate()
print(stream.render('xhtml'))

However, you should probably change list_of_ints to my_list, and iterate over it directly. Or even better, if you must know the index of each item from within my_list, use enumerate:

from genshi.template import MarkupTemplate
template_text = """
<html xmlns:py="http://genshi.edgewall.org/" >
    <tr py:for="(index, item) in enumerate(list_of_ints)">
         <py:choose test="index">
             <py:when index="0"><td>index=${index}, item=${item} is NOT OK</td></py:when>
             <py:otherwise><td>${index}, item=${item} is OK</td></py:otherwise>
         </py:choose>
    </tr>
</html>
"""
tmpl = MarkupTemplate(template_text)
stream = tmpl.generate(list_of_ints=range(0, 25))
print(stream.render('xhtml'))

Of course, these examples were made to run from a python interpreter. You can modify this to work with your setup easily.

HTH

Upvotes: 0

Related Questions