Roland Tritsch
Roland Tritsch

Reputation: 81

Scala Play - How to convert a list of Scala Strings into an Array of javascript Strings (avoiding the " issue)?

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?

Upvotes: 8

Views: 1786

Answers (2)

trungtv
trungtv

Reputation: 31

Don't forget @Html.

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

Upvotes: 3

Julien Lafont
Julien Lafont

Reputation: 7877

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

Upvotes: 5

Related Questions