2012-01-24 56 views
30

我嘗試做的斑馬條紋:增量聲明整型變量

{% set counter = 0 %} 
{% for entity in entities %} 
    <tr class="{{ cycle(['odd', 'even'], counter) }}"> 
    {% counter++ %} 

,但我得到的錯誤:

Unexpected tag name "counter" (expecting closing tag for the "for" tag defined near line 11)

可能有人給我解決?

[編輯]

我壞的解決方案是很容易的:

{% set counter = counter + 1 %} 
+0

這是表格嗎? '

' – zkent

回答

37

有做你想要的東西更簡單的方法:

{{ cycle(["even", "odd"], loop.index) }} 

loopdocs好吃的東西。

5

如果你想擁有在HTML的完全控制,你可以試試這個:

{% if loop.index is divisibleby(2) %} 
    ... 
{% endif %} 

你可以在這裏閱讀:http://twig.sensiolabs.org/doc/tests/divisibleby.html

注意loop.index用「原樣」,它不會引用變量,而是指向for循環的隱藏索引。

+0

非常好!謝謝 – Barno