In Play! 1, it was possible to get the current index inside a loop, with the following code:
#{list items:myItems, as: \'item\'}
Item ${item_in
Yes, zipWithIndex
is built-in feature fortunately there's more elegant way for using it:
@for((item, index) <- myItems.zipWithIndex) {
<li>Item @index is @item</li>
}
The index is 0-based, so if you want to start from 1 instead of 0 just add 1 to currently displayed index:
<li>Item @{index+1} is @item</li>
PS: Answering to your other question - no, there's no implicit indexes
, _isFirst
, _isLast
properties, anyway you can write simple Scala conditions inside the loop, basing on the values of the zipped index (Int
) and size
of the list (Int
as well).
@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>
}
The answer in the linked question is basically what you want to do. zipWithIndex
converts your list (which is a Seq[T]
) into a Seq[(T, Int)]
:
@list.zipWithIndex.foreach{case (item, index) =>
<li>Item @index is @item</li>
}