0

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>    
2
  • 1
    Why currentUser need to be implicit? You create it, as soon as the page is loaded? I'm asking this, because if you are creating a 'new User', how do you know what is her id? permissions, etc. Shouldn't it be passed over from the controller? Commented Jul 11, 2018 at 2:27
  • Twirl is not preferred for such operations. You can create json in code and pass that as parameter. playframework.com/documentation/2.6.x/ScalaJson Commented Jul 11, 2018 at 10:36

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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 -->

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.