2014-11-04 79 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