Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...