Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - How do I pass a Java Map<Long, Integer> 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) variables are, at the top of the page:

@(workingVar1: String, workingVar2: Int, mapVar: Map[Long, Integer])

But developer tools in google chrome highlights this part of the javascript (embedded in home.scala.html's head):

var myMap = @mapVar;

With the error Uncaught SyntaxError: Unexpected token =

So none of the javascript works. What is the correct way to pass this map in?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...