Search code examples
javascalaplayframeworkplayframework-2.0playframework-2.2

How to render a list/stringbuilder to template


I have a list of objects that i retrieved from a JSon File. I am trying to render them into the index.scala.html to create a table, but I am unable to do so. Help?

I tried @(StringBuilder: mystring) and it did not work.

I was wondering after I am successful (hopefully) in rendering the list/stringbuilder into the template how do I use it to make a table?

public static Result index() {
  List<MetaModel> arr = getData();

  StringBuilder myString = new StringBuilder();
  for(MetaModel model : arr)
  {
    myString.append(model.toString());
  }

  return ok(index.render(myString.toString()));
}  

Solution

  • My Java is a bit rusty, anyway you are calling toString() on the StringBuilder but in the template you have @(StringBuilder: mystring) which is the wrong type and the wrong syntax, it should be @(myString: String).

    If instead you want to pass the StringBuilder to the template, simply avoid calling toString and bind the variable like this @(mystring: StringBuilder).

    For Lists, simply bind the variable in the template @(integers: List[Int]) and then use map

    <ul>
      @integers.map { someInt => <li>@someInt</li> }
    </ul>
    

    or simpler @for function:

    <ul>
       @for( someInt <- integers) { <li>@someInt</li> }
    </ul>
    

    More info and also some examples are also on the Play documentation for Java.