2014-11-04 38 views
0

我试图使用一个循环内选择语句的列表中进行选择,我需要填充表这种方式:潘岳:用绳子

<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> 

我就行了<py:choose...>一个错误:

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

但我不明白如何使用choose语句! 如果我想为C类(而且在我看来,更符合逻辑的)我需要只写:

<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> 

你能帮助我吗? 哦,my_list是一个字符串列表。然后,如果字符串是0那么对我而言不是好的,其他的都是好的。

回答

0

py:choose之内,您没有访问my_list的Ith项。相反,i设置为等于范围内的int。我认为这是一个人为的例子,并且您试图访问Ith的值my_list。在这种情况下,您应该重复执行my_list而不是使用range

下面是使用您当前的方法的示例。该错误是内py:choose本身:

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')) 

但是,你应该改变list_of_intsmy_list,并直接遍历它。 甚至更​​好,如果你必须知道每个项目从my_list中的索引,使用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')) 

当然,作了这些例子从一个Python解释器运行。您可以修改此以便轻松地使用您的设置。

HTH

+0

谢谢!我们接近解决方案......我需要知道在第I个刺中是否写有'0',那么我需要py:当my_list [i]值而不是索引时。现在我有同样的错误,但在py:when行,因为我写道:' ...'I甚至尝试用 user2174050 2014-11-05 12:11:15

+0

也许你不理解枚举或for循环。要将第二个示例更改为所需,将'list_of_ints'更改为'my_list',并用''替换''。 – VooDooNOFX 2014-11-05 21:25:54