binshi binshi - 3 months ago 22
Scala Question

Play framework Twirl template comparing javascript element and scala variable

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>

Answer

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