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

2024-04-03

游戏中! 1、可以在循环中获取当前索引,代码如下:

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

Play2 中有类似的功能吗?

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

同样的问题_isLast and _isFirst.

ps: 这个问题 https://stackoverflow.com/questions/12251504/play2-template-incrementing非常相似,但解决方案意味着修改代码以返回Tuple (item, index)而不仅仅是一个列表item.


Yes, zipWithIndex is built-in幸运的是,还有更优雅的使用方式:

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

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

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

PS:回答你的另一个问题 - 不,没有隐含的indexes, _isFirst, _isLast属性,无论如何,您可以根据压缩索引的值在循环内编写简单的 Scala 条件(Int) and size列表中的(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>
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取 Play 中当前循环的索引! 2 Scala 模板 的相关文章

随机推荐