在Twig循环中检查第n个元素的最佳方法是什么?

时间:2014-04-05 01:39:54

标签: twig

所以目前以下代码执行以下操作:

  • class" custom-border-right-blog"如果item位于3列行的第一列或第二列
  • class" last"如果item是循环中的最后一个。

    <div class="large-4 medium-12 small-12 columns {% if (loop.index is divisibleby(3) == false) %}custom-border-right-blog{% endif %}{% if loop.last %} last {% endif %}">
    

有更清洁的方法来实现这一目标吗?我对树枝很新,而我现在这样做的方式对我来说似乎相当混乱。

2 个答案:

答案 0 :(得分:1)

在缩短代码以提高可读性方面,我会假设这一点:

<div class="large-4 medium-12 small-12 columns {{ (loop.index % 3) ? 'custom-border-right-blog' : 'last' }}">

<强>更新

如果你真的只需要最后一个元素的类,那就更灵活了:

<div class="large-4 medium-12 small-12 columns {{ (loop.last) ? 'last' : 'custom-border-right-blog' }}">

答案 1 :(得分:1)

您可以使用cycle twig函数根据模数应用类。当您为oddeven行应用不同的类时,这非常有用。在您的情况下,这看起来像:

class="(...) {{ cycle(['custom-border-right-blog', 'custom-border-right-blog', ''], loop.index) }} (...)"

无论如何,在您的具体情况下,您申请课程的方式对我来说是最好的。

相关问题