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?

1
  • JSON might be the right way to go, but if you'd like something even more basic, have a look here where the second answer uses mkString. With the needed caveat about strings including quotation marks, etc. Commented Jun 28, 2014 at 9:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.