Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playframework: Looping over a list

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("---------------------");
        }
like image 595
Gaurav Sharma Avatar asked Jun 03 '13 19:06

Gaurav Sharma


3 Answers

Here is a working example,

@(list: List[String])

@for(value <- list){

}
like image 38
Md Samiul Alim Sakib Avatar answered Nov 10 '22 23:11

Md Samiul Alim Sakib


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>
    }
}
like image 187
Aerus Avatar answered Nov 10 '22 22:11

Aerus


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).

like image 8
Richard Close Avatar answered Nov 10 '22 22:11

Richard Close