Jeffrey Keehr
Jeffrey Keehr

Reputation: 67

How do I pass a JSONObject to a Play Framework for Java template's javascript?

I am working with the Play framework (2.4) for Java. I want to pass a JSONObject to a javascript used inside one of the Play view templates.
On the Java side I prepare the JSONObject, like so:

(Keep in mind that this is a test vehicle.)

    public static Result showBusinesses(){
    List<Item> list = new ArrayList<Item>();
    Item r = new Item();
    r.id = "23234";
    r.name = "Joes hardware";
    Item s = new Item();
    s.id = "23254";
    s.name = "Martys collision";
    list.add(r);
    list.add(s);
    return ok(views.html.wheel.render(getJSONObject(list)));
}

public static JSONObject getJSONObject(List<Item> list){
    JSONObject jsonObject = new JSONObject();
    try{
        for (int i = 0; i < list.size(); i++) {
        jsonObject.put(list.get(i).id, list.get(i).name);
        }
    }catch (JSONException e) {

    }
    return jsonObject;
}

In my Play template, I accept the JSONObject parameter:

@(item : org.json.JSONObject)

@import helper._
@import helper.twitterBootstrap._
@import play.api.libs.json.Json 

...

So far, so good.

Until I attempt to use the object in my javascript:

If I place my object, @item, anywhere in the template besides inside the javascript, I get this: {"23254":"Martys Pancakes","23234":"Joes place"}; which looks like a properly formed var to me.

I am inserting the JSONObject into the javascript like this:

<script type="text/javascript">

 businesses = @item;

and I expect that to translate like this:

businesses = {
    "23332"  : "Joe's hardware",
    "56755"  : "Marty's collision"
};

And yet the object does not behave as expected. I suspect that I am not passing the parameter to the javascript in the correct way.

Can anyone enlighten me? Thanks.

Upvotes: 1

Views: 1256

Answers (1)

Jeffrey Keehr
Jeffrey Keehr

Reputation: 67

I found the answer to my own question. It ended up being fairly simple. First of all, you don't need to mess with JSON. You pass a standard Java List to the Play template. Then you iterate through that list inside the Javascript variable curly braces. Here is the template code:

@(businesses: List[Business])

@import helper._
@import helper.twitterBootstrap._

...

<script type="text/javascript">

places = {
    @for((item, index) <- businesses.zipWithIndex) {
                @if(index != businesses.size-1) {
                "@item.id" : "@Html(item.name)",} 
                else {"@item.id" :      "@Html(item.name)"}
     }              

};

I used the built-in zipWithIndex because I needed commas separating every line but the last. The @Html() was needed to escape all the special chars that HTML needs to have translated. Once the javascript runs, you end up with your variable:

places = {
"345" : "Joe's Hardware",
"564" : "Jan's Party Store"
}

Upvotes: 1

Related Questions