8

When converting a Scala list of Strings into a javascript Array of Strings with the Play template engine, you probably start with something like this ...

var strArray = [@scalaListOfStrings.mkString(",")];

... and will find out that this is not working, because the quotes around the strings are missing. Next you might try something like this ...

var strArray = [@scalaListOfStrings.map(s => "\"" + s + "\"").mkString(",")];

... only to find out that this will wrap the strings in " and not ". The only way I was able to make this work was with ...

var strArray = [@Html(scalaListOfStrings.map(s => "\"" + s + "\"").mkString(","))];

... and my question is: Is this the best/only way to do this?

2 Answers 2

5

You can rely on the Json.toJson() method to make the conversion

@import play.api.libs.json._

var strArray = @Json.stringify(Json.toJson(List("hello", "world", "everybody")))
Sign up to request clarification or add additional context in comments.

Comments

3

Don't forget @Html.

@Html(Json.stringtify(Json.toJson(Scala object)))

1 Comment

stringtify or stringify? what imports are you using?? sorry to draw the attention, i was just passing through, trying to make some things works, and this code doesn't work in scala play 2.2.2. BTW: the Html has to be imported?

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.