2

As shown in the code sample below I want to compare a javascript element inside a scala helper element. However it always returns false even when the element "abcde" is present. How can I get the javascript value inside the scala helper element other than using tags?

@(appSeq:Seq(String))
<script>
var app = 'abcde'
@if(appSeq.contains(<script>app</script>)) {
   alert('true');
} else {
   alert('false');
}
</script>
binshi
  • 1,248
  • 2
  • 17
  • 33

2 Answers2

4

It is not possible for this reason:

  • var app = 'abcde' is evaluated in the JS VM
  • the XML literal <script>app</script>) is evaluated in the Java VM

So since they are two different contexts you can't share a variable from JS to Scala. What you can do is pass a variable from Scala to JS, since Scala code is evaluated first and all the values will be rendered in the template.

You need either to hard code 'abcde' in the Scala XML or better assign it to a Scala value like:

@(appSeq:Seq(String))
@app="abcde"
<script>
var app = "@app"
@if(appSeq.contains(<script>$app</script>)) {
   alert('true');
} else {
   alert('false');
}
</script>
pietro909
  • 1,811
  • 1
  • 19
  • 26
0

Your question is not clear much but using javascript variable in scala is not possible. View is compiled and then you're passing some variables to this view as a result play/twirl render it as http response. After that you're in front end zone, there is no scala at all.

So its better to move your logic in frontend. If you only want to contain checks once then you can accomplish it like this;

@(appSeq:Seq[String], app: String)
<script>
var app = "@app"

@if(appSeq.contains(s"<script>$app</script>")) {
alert('true');
} else {
alert('false');
}
</script>

But if you want to do this contain check again again in front end. It's better to pass appSeq as javascript array into front end and do javascript contains on javascript object.

Here is a link to explain contain for array in js.

Community
  • 1
  • 1
Fatih Donmez
  • 4,319
  • 3
  • 33
  • 45