Skip to content Skip to sidebar Skip to footer

How Do I Pass A Java Map Into Scala-play?

In my play framework project I have a confirmed functional Java map of the form Java that is passed to a html page home.scala.html The map variable is passed in as other (working)

Solution 1:

You can use Java/Scala variables in Twirl Scala templates and both are executed on the server side. Now on server side Twirl engine translates Java object to something (which probably isn't what you want) and in this form is passed to client, and then this JavaScript is executed.

You want to make sure that client will receive valid JavaScript code. To assign proper value, you will have to mix some JSON libraries, which will help you assign value in a proper way.

Eg. on the controller side:

...
Map<Long, Integer> map = new HashMap<>();
map.put(1L, 2);
map.put(3L, 3);
String yourMap = Json.stringify(Json.toJson(map));

Now you want to pass yourMap to view, and then you will assign to myMap using @Html as we want it as raw content fragment:

@(workingVar1: String, workingVar2: Int, mapVar: String)
var myMap = @Html(mapVar);

Try and let me know if it helped.

Solution 2:

An inelegant but functional solution is as follows:

Bring in the Java Map as a string:

var stringMap = "@mapVar";

Removes the braces and spaces inserted into the string unnecessarily

stringMap = stringMap.replace(/{/g,'');stringMap = stringMap.replace(/}/g,'');stringMap = stringMap.replace(/ /g,'');

Split the mapString by , and for every pair split again by =, extracting keys and values as you go. These will need to be parsed to their correct data-types before adding to a javascript array jsArr:

var pairArray = mapString.split(",");
  pairArray.forEach(function(pair) {
      var values = pair.split("=");
      var longString = values[0];
      var intString = values[1];
      var myLong = parseFloat(longString);
      var myInt = parseInt(intString);
      jsArr.myLong = myInt;
}

Where jsArr has been defined previously.

Post a Comment for "How Do I Pass A Java Map Into Scala-play?"