2
votes

I'm using Scala Play Framework 2.1 for my website. I'd like to be able to pass an array or list to the client-side code for subsequent processing after the page is loaded. The list is essentially a bunch of things to later request from the server. My purpose is for the web page to be displaying data as it comes in.

The code below in a template works but it feels kludgy. Is there a better way to do this?

<script>
    var items = [ @results.map{ res =>
        "@res.item",
    } ""]
</script>

Here's what I eventually want to do on the client-side:

for (var i = 0; i < items.length; i++)
{
  var item = items[i]

  jQuery.ajaxQueue({
    url: "/dataJson",
    data: {item : item}
  }).done(function( data ) {
    addColumn(data)
  });

}

2
show us a snippet of the code you WANT to achieve finally. - biesior

2 Answers

2
votes

Assumming that results.map(_.item) is a list of strings:

@import play.api.libs.json._

<script>
    var items = @Html(Json.toJson(results.map(_.item)).toString);
</script>

//result: var items = ["a","b","c"];
1
votes

I used something similar:

<script>
  var items = new Array();
  @for((result: String, index) <- results.zipWithIndex) {
    items[@index] = "@result";
  }
</script>

But I agree that it's a bit kludgy, especially when you need to escape special chars...

// Multiline js escape can be done this way:
.replaceAll("\n", "\\\\\n")