简体   繁体   中英

Playframework [Scala]: Create JSON List from Scala object in Twirl

I have a list of objects, of which I only need each object's ID (of type String ) property.

In the view, I have Google Tag Manager set up and need to pass the IDs of each object as a JSON array. I'm not sure how to do this in Twirl because I'm working with a Scala object inside a script tag. I need each string to quotation marks around it, separated by commas, and have brackets on each side like ["one","two","three"] . Is there any way to do this?

The permissions value is what's giving me trouble:

@()(implicit currentUser: User = new User())
<script>
dataLayer = [{
   'userId': '@currentUser.userId',
   'firstName': '@currentUser.firstName',
   'lastName': '@currentUser.lastName',
   'permissions': ['@currentUser.permissions.map(p => p.permissionId).mkString(",")']
}];
</script>    

I suggest when passing data this way, that you build the object ahead of time like this:

<script>
  dataLayer = @Html(Json.toJson(Seq({
     "userId" -> currentUser.userId
     "firstName" -> currentUser.firstName,
     "lastName"" -> currentUser.lastName
     "permissions" -> currentUser.permissions.map(_.permissionId)
  )).toString);
</script>

an alternative is to predefine some implicit Format[User] and import that to write the Json:

@import simpleUserJsonFormat
<script>
  dataLayer = @Html(Json.toJson(Seq(currentUser)).toString);
</script>

I was able to get a regular JSON list by combining the Json library in Play with Javascript.

@()(implicit currentUser: User = new User())

@import play.api.libs.json._
<script>
  var rawPermissions = '@Json.toJson(currentUser.permissions.map(p => p.permissionId))';
  var permissions = JSON.parse(rawPermissions.replace(/&quot;/g, "\""));
  dataLayer = [{
     'userId': '@currentUser.userId',
     'firstName': '@currentUser.firstName',
     'lastName': '@currentUser.lastName',
     'permissions' : permissions
  }];
</script>
<!-- Google Tag Manager -->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM