2012-11-29 24 views
1

我想要以交替方向呈現HTML塊。這是正確的語法,以獲得循環的當前值?測試周期的當前值

{% if ({{ cycle(['odd', 'even']) }} == 'odd') %} 
foo 
{% elseif %} 
bar 
{% endif %} 

回答

2
  1. cycle(['odd', 'even'])不應該是內部{{ }}if 聲明
  2. cycle()應該有第二個參數給出計數
  3. {% elseif %}要麼有一個條件或改爲循環量{% else %}

這是什麼你應該做的就是代碼,你想讓它工作(循環10次):

{% for i in 0..9 %} 
    {% if cycle(['odd', 'even'], i) == 'odd' %} 
     foo 
    {% else %} 
     bar 
    {% endif %} 
{% endfor %} 

如果你想爲循環對象可以使用loop.index(從1開始),而不是i

{% for object in objects %} 
    {% if cycle(['even', 'odd'], loop.index) == 'odd' %} 
     foo 
    {% else %} 
     bar 
    {% endif %} 
{% endfor %} 

loop.index0(開始於0):

{% for object in objects %} 
    {% if cycle(['odd', 'even'], loop.index0) == 'odd' %} 
     foo 
    {% else %} 
     bar 
    {% endif %} 
{% endfor %}