在 Play 中获取当前循环的索引!2 Scala 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14608334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:53:57  来源:igfitidea点击:

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

scalaplayframework-2.0

提问by Romain Linsolas

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

在玩!1,可以使用以下代码获取循环内的当前索引:

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

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

在 Play2 中是否有类似的东西来做这样的事情?

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

Same question for the _isLastand _isFirst.

对于同样的问题_isLast_isFirst

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

ps:这个问题很相似,但解决方案暗示修改代码以返回一个Tuple (item, index)而不是一个列表item

回答by biesior

Yes, zipWithIndexis built-infeature fortunately there's more elegant way for using it:

是的,幸运的zipWithIndex内置功能有更优雅的使用方式:

@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:

索引是基于 0 的,因此如果您想从 1 而不是 0 开始,只需将 1 添加到当前显示的索引:

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

PS:Answering to your other question - no, there's no implicit indexes, _isFirst, _isLastproperties, anyway you can write simple Scala conditions inside the loop, basing on the values of the zipped index (Int) and sizeof the list (Intas well).

PS:回答您的另一个问题 - 不,没有隐式indexes, _isFirst,_isLast属性,无论如何您可以根据压缩索引 ( Int) 和size列表 ( )的值在循环内编写简单的 Scala 条件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>
}

回答by Dan Simon

The answer in the linked question is basically what you want to do. zipWithIndexconverts your list (which is a Seq[T]) into a Seq[(T, Int)]:

链接问题中的答案基本上是您想要做的。 zipWithIndex将您的列表(即 a Seq[T])转换为 a Seq[(T, Int)]

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