在Play中获取当前循环的索引! 2 Scala模板 [英] Getting the index of the current loop in Play! 2 Scala template

查看:78
本文介绍了在Play中获取当前循环的索引! 2 Scala模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在播放!如图1所示,可以使用以下代码在循环内获取当前索引:

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}

在Play2中有类似的东西可以做类似的事情吗?

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

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

_isLast_isFirst相同的问题.

ps:此问题非常相似,但是该解决方案暗示要修改代码以返回一个Tuple (item, index)而不只是item的列表.

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.

推荐答案

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

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

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

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

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

这篇关于在Play中获取当前循环的索引! 2 Scala模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆