Getting a key from a For loop with a list (not a map)

I have a list of models (list items) that I scroll in my template:

@for(item <- items) {
    // ...
}

I would like to get the key / index position itemin itemsfor two reasons:

  • I will show something like Item n° @key
  • I would like to show only 1/2 element (I guess: if (@key % 2))

How can I get the key / index when using a list, not a map?

thanks for the help

+3
source share
3 answers

You can pin the list with your indexes:

@defining(List("foo", "bar", "baz")) { items => 
  @for((item, i) <- items.zipWithIndex if i % 2 == 0) {
    @item no @i <br/>
  }
}

What prints:

foo no 0 
baz no 2 
+11
source

you can use .zipWithIndex:

@for((item,i) <- items.zipWithIndex) {
    // ...
}

The index will be based on 0.

+4
source

- "". var , 0 .

Another option is to use zipWithIndex in your list before repeating it. Then, instead of getting the elements in a loop variable, you actually have a tuple consisting of the element and its index in the list.

+1
source

All Articles