I have a list that I'm passing back to the view.
public static Result index() {
List<String> list = new ArrayList<String>();
list.add("idea 1");
list.add("idea 2");
list.add("idea 3");
list.add("idea 4");
list.add("idea 5");
list.add("idea 6");
list.add("idea 7");
return ok(index.render(list));
}
I'd like to iterate over it 3 at a time so that it's displayed like so:
<ul>
<li>idea 1</li>
<li>idea 2</li>
<li>idea 3</li>
</ul>
<ul>
<li>idea 4</li>
<li>idea 5</li>
<li>idea 6</li>
</ul>
<ul>
<li>idea 7</li>
</ul>
I'm unable to figure out how to do this using the for loop.
I have the Java code for this, just unable to translate this to the Play framework template code:
int size = list.size();
int loopSize = (int) Math.ceil(size / 3.0);
int counter = 0;
for(int j = 0 ; j < loopSize; j++) {
System.out.println("---------------------");
for (int i = 0; i < 3; i++) {
if(counter < size) {
System.out.println(list.get(counter));
counter++;
} else {
break;
}
}
System.out.println("---------------------");
}
Here is a working example,
@(list: List[String])
@for(value <- list){
}
This should work:
@(list: List[String])
@for(index <- 0 until list.size){
@if(index % 3 == 0){
<ul>
}
<li>@list(index)</li>
@if(index % 3 == 2 || index == (list.size - 1)){
</ul>
}
}
Here's a more Scala-esque version:
@(list: List[String])
@list.grouped(3).map { group =>
<ul>
@group.map { item =>
<li>@item</li>
}
</ul>
}
(The other response answers the question as asked more directly, particularly as the questioner may not be using Scala in the rest of his project).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With