获取电流环的指数播放! 2斯卡拉模板(Getting the index of the curr

2019-07-19 00:31发布

在玩游戏! 1,有可能获得当前指数在一个循环中,用下面的代码:

#{list items:myItems, as: 'item'}
    <li>Item ${item_index} is ${item}</li>
#{/list}

是否有Play2等效的,做这样的事情?

@for(item <- myItems) {
    <li>Item ??? is @item</li>
}

对于同样的问题_isLast_isFirst

PS: 这个问题是非常相似的,但解决方案隐含修改代码返回一个Tuple (item, index) ,而不仅仅是一个列表item

Answer 1:

是的, zipWithIndex内置的功能,好在有使用它更优雅的方式:

@for((item, index) <- myItems.zipWithIndex) {
    <li>Item @index is @item</li>
}

该指数是从0开始的,所以如果你想从1而不是0开始只加1到当前显示的索引:

<li>Item @{index+1} is @item</li>

PS:在回答你的其他问题-不,有没有隐含的indexes_isFirst_isLast性质,反正你可以写在循环中简单的斯卡拉条件,立足于压缩指数(的价值Int )和size列表( Int为好)。

@for((item, index) <- myItems.zipWithIndex) {
    <div style="margin-bottom:20px;">
        Item @{index+1} is @item <br>
             @if(index == 0) { First element }
             @if(index == myItems.size-1) { Last element }
             @if(index % 2 == 0) { ODD } else { EVEN }
    </div>
}


Answer 2:

在链接的问题的答案基本上是你想要做什么。 zipWithIndex转换列表(其为Seq[T]转换成Seq[(T, Int)]

@list.zipWithIndex.foreach{case (item, index) =>
  <li>Item @index is @item</li>
}


文章来源: Getting the index of the current loop in Play! 2 Scala template