23

In Play! 1, it was possible to get the current index inside a loop, with the following code:

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

Is there an equivalent in Play2, to do something like that?

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

Same question for the _isLast and _isFirst.

ps: this question is quite similar, but the solution implied to modify the code to return a Tuple (item, index) instead of just a list of item.

Community
  • 1
  • 1
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273

2 Answers2

61

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>
}
biesior
  • 55,576
  • 10
  • 125
  • 182
  • 1
    Ok, in fact I didn't understand that the `zipWithIndex` was a *built-in* feature. I thought that I had to implement it on my controller or object. Thanks. – Romain Linsolas Jan 31 '13 at 08:06
  • is there something like this for Scala (not Play)... just want to get my `i` back – Adrian Apr 10 '13 at 14:29
  • Unfortunately this example is not incrementing properly. Iget this: Item 30 is EVEN Item 5 is ODD Item 24 is EVEN Item 32 is EVEN Item 8 is EVEN Item 37 is Last element ODD Item 36 is EVEN Item 23 is ODD Item 34 is EVEN Item 22 is EVEN Item 6 is EVEN Item 3 is ODD Item 29 is ODD Item 35 is How can i get a proper order like 0...10 ? – dc10 Apr 27 '15 at 14:01
8

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>
}
Dan Simon
  • 12,891
  • 3
  • 49
  • 55
  • yes, but I wanted to know if there is a built-in feature for that, instead of changing my own code... – Romain Linsolas Jan 30 '13 at 16:10
  • @romaintaz, play 2 allows Scala expressions. Therefore, it comes down to whether scala has such a feature. – jmg Jan 30 '13 at 16:12