Sebastian Perez
Sebastian Perez

Reputation: 456

How to get index from a Model Class iteration in a Playframework Scala Template

I'm trying a simple thing with the TODO tutorial.

I want to show the task list in a table but I can't find a way to get the index in the iteration.

@tasks.map { task =>
                <tr>
                    <td><!-- DISPLAY INDEX HERE --></td>
                    <td>
                        @form(routes.Application.deleteTask(task.id.get)) {
                            <input type="submit" class="btn btn-primary remove_task" value="-">
                        }
                        @task.label
                    </td>
                </tr>
            }

Any ideas?

Upvotes: 2

Views: 238

Answers (2)

Ratan Sebastian
Ratan Sebastian

Reputation: 1892

You can use @tasks.zipWithIndex.map { case (task, index) => ... }

Upvotes: 4

pedrofurla
pedrofurla

Reputation: 12783

You can use the zipWithIndex. For example:

scala> List("A","B","C")
res4: List[java.lang.String] = List(A, B, C)

scala> res4.zipWithIndex
res5: List[(java.lang.String, Int)] = List((A,0), (B,1), (C,2))

Your final code would be, notice I renamed the task variable:

@tasks.zipWithIndex.map { tuple =>
                <tr>
                    <td>tuple._2</td>
                    <td>
                        @form(routes.Application.deleteTask(tuple._1.id.get)) {
                            <input type="submit" class="btn btn-primary remove_task" value="-">
                        }
                        @tuple._1.label
                    </td>
                </tr>
            }

Upvotes: 1

Related Questions