Is there a simpler way of doing this?
$(document).ready(function () {
var jsArray = []
@if(scalaList != null) {
@for(id <- scalaList) {
jsArray.push('@id');
}
}
...
}
It's as simple as the following:
import play.api.libs.json.Json
val jsArr: JsValue = Json.toJson(scalaList)
You can also do that within a template:
@(list: List[Any])
@import play.api.libs.json.Json
<script type="text/javascript">
$(document).ready(function () {
var jsArr = @Json.toJson(list);
console.log(jsArr);
});
</script>
You can use mkString for this.
$(document).ready(function () {
var jsArray = @if(scalaList != null) {
[ @scalaList.mkString(",") ]}
else {[]};
}
You should omit this if statement in view. Instead of this, check null in controller and put empty list to view, so this code can be more simpler in view
$(document).ready(function () {
var jsArray = [ @scalaList.mkString(",") ];
}
You don't need this quotes ' ' around id. In javascript 1 == '1' is true
Have you tried something like:
var jsArray = new Array(@scalaList.map(x => "\"" + x + "\"").mkString(","));
or you can use a literal like
var jaArray = [ var jsArray = [@scalaList.map(x => "\"" + x + "\"").mkString(",")];
Also the if
check is not required. For
comprehensions are smart like that
$(document).ready(function () {
var jsArray = [@scalaList.map(x => "\"" + x + "\"").mkString(",")];
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With