2

Ok so I have a template in Play! that receives a List as a parameter:

@(actions : List[RecipientAction])

RecipientAction is just a regular case class with a couple of fields. Within the template, I have a <script> tag where I want to use D3 to make a line chart. Inside the script I want to populate a JavaScript array with objects that contain the properties stored in RecipientAction in order to use them for my line chart later. I currently have this code:

      testArray2=[];

      for(var i=0; i < @actions.length;i++){
        testArray2[i]= {};
        testArray2[i].eventAt= @actions(i).eventAt.toString();
        testArray2[i].action= @actions(i).action.id;

      }

When i run it, i get the error "not found: value i". This is because i is a client side variable while actions is a server side variable, so scala cannot find i. What would be the best way to work around this and successfully populate the array?

  • JSON might be the right way to go, but if you'd like something even more basic, have a look [here](http://stackoverflow.com/questions/15520703/how-to-convert-scala-list-to-javascript-array) where the second answer uses mkString. With the needed caveat about strings including quotation marks, etc. – wwkudu Jun 28 '14 at 09:02

1 Answers1

3

You need to create a JSON serializer for your RecipientAction, then you'll just be able to print the list as JSON in the template. Say it looks something like this..

import play.api.libs.json._

case class RecipientAction(id: Int, description: String)

object RecipientAction {
     // Define a `Writes` for `RecipientAction`
     implicit val writes: Writes[RecipientAction] = Json.writes[RecipientAction]
}

I used one of the JSON macros included with Play that will automatically create a Writes for a case class, since all we care about is printing the list.

Then in your template:

@(actions : List[RecipientAction])
@import play.api.libs.json.Json

<script type="text/javascript">
    var testArray = @Html(Json.stringify(Json.toJson(actions)));
</script>

The definition of an implicit Writes is required so that Json.toJson knows how to convert the class to JSON. For more about Json serialization/deserialization see the documentation.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138