2011-12-26 99 views
27

你好,我想这样做财产以后这样的:在一个循环计数

<?php $count = 0; foreach($a as $v): $count++; ?> 
    <?php if ($count%2 == 0): ?> 
    ... 
    <?php endif; ?> 
<?php endforeach; ?> 
在树枝

{% for v in a %} 
    {% if ??? is even %} 
    ... 
    {% endif %} 
{% endfor %} 

但我怎么能有一个变量,循环发展?

回答

56

显然枝杈定义了一些loop variables里面的for循环:

{% for v in a %} 
    {% if loop.index0 is even %} 
     ... 
    {% endif %} 
{% endfor %} 
24

如果你使用它的造型,你可以这样做:

{% for v in a %} 
    <div class="link {{ cycle(['even', 'odd'], loop.index0) }}"> 
    </div> 
{% endfor %} 
+1

感谢,正是我一直在寻找。然而,只是一个小的修正:它应该是'cycle(['even','odd'],loop.index0)',因为使用了'loop.index0'。当你使用'loop.index0'时,你说你有一个“第零”行,零是一个偶数。所以,在这种情况下,你的第零排是平坦的,第一排是奇数,第二排是偶数,等等。 – cmt 2013-08-03 06:25:34

+0

非常整洁的解决方案,尤其是如果你需要与“偶数和奇数”不同的东西,例如“1st,2nd和3rd ”。现在,性能呢?也许使用'{%if loop.index0 is even%}'比用{{循环(['even','odd'],loop.index0)}}''知道是否有任何理由选择一种解决方案,还是最终并不重要,将会很有趣。 – Arvid 2017-01-05 12:41:37