Populate Javascript array using Scala List in Play framework template -


ok have template in play! receives list parameter:

@(actions : list[recipientaction])

recipientaction regular case class couple of fields. within template, have <script> tag want use d3 make line chart. inside script want populate javascript array objects contain properties stored in recipientaction in order use them line chart later. have code:

      testarray2=[];        for(var i=0; < @actions.length;i++){         testarray2[i]= {};         testarray2[i].eventat= @actions(i).eventat.tostring();         testarray2[i].action= @actions(i).action.id;        } 

when run it, error "not found: value i". because i client side variable while actions server side variable, scala cannot find i. best way work around , populate array?

you need create json serializer recipientaction, you'll able print list json in template. looks this..

import play.api.libs.json._  case class recipientaction(id: int, description: string)  object recipientaction {      // define `writes` `recipientaction`      implicit val writes: writes[recipientaction] = json.writes[recipientaction] } 

i used 1 of json macros included play automatically create writes case class, since care printing list.

then in template:

@(actions : list[recipientaction]) @import play.api.libs.json.json  <script type="text/javascript">     var testarray = @html(json.stringify(json.tojson(actions))); </script> 

the definition of implicit writes required json.tojson knows how convert class json. more json serialization/deserialization see documentation.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -