Nadir Muzaffar
Nadir Muzaffar

Reputation: 4842

Bootstrapping JSON data into Scala PlayFramework templates

Goal is to go from a Model/ViewModel written in Scala to raw JSON that can be bootstrapped into the view template so as to avoid making requests for the JSON data after the page load.

And example of what I've been playing around with but I haven't had much luck:

@(todos: play.api.libs.json.JsValue)
@import play.api.libs.json.Json

<html>
   <head>...</head>
   <body>...</body>

   <script>
      var todos = JSON.parse(' @Json.stringify(todos) ');
   </script>
</html>

Basically its spitting out a lot of quoted text to the effect of:

[{&quot;id&quot;:&quot;:&quot;294858e2-c9eb-4f50-9eac-47b257573d83&quot;}] 

Haven't had much luck with Google or the PlayFramework docs so I'd love some help.

Upvotes: 5

Views: 1883

Answers (1)

Mikesname
Mikesname

Reputation: 8901

The Play template engine will escape any strings you render to HTML, which will thoroughly mangle your JSON.

To output it verbatim, do @Html(Json.stringify(todos)), as described here.

Upvotes: 8

Related Questions