Getting the index of the current loop in Play! 2 Scala template

后端 未结 2 1995
轻奢々
轻奢々 2020-12-01 08:25

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
  • 2条回答
    •  醉话见心
      2020-12-01 08:42

      Yes, zipWithIndex is built-in feature fortunately there's more elegant way for using it:

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

      The index is 0-based, so if you want to start from 1 instead of 0 just add 1 to currently displayed index:

    • Item @{index+1} is @item
    • 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) {
          
      Item @{index+1} is @item
      @if(index == 0) { First element } @if(index == myItems.size-1) { Last element } @if(index % 2 == 0) { ODD } else { EVEN }
      }

    提交回复
    热议问题