I have a js variable in the index.html file and i want to do an assignment like this:
var names=["${stateNames}"];
where stateNames is a Java List containing state names. How do i do an assignment like the above so that names now has all the state names contained in stateNames ? The variable stateNames is passed to index.html from the play controller.
Is there any way to do the above ??
If you are using the Groovy templates, this is trivial, because you have access to Groovy's collection methods :
var names=[${stateNames.collect{'"'+it+'"'}.join(",")}];
collect
transforms your collection, join
creates one big String separated by the given String.
Scala version for completeness' sake:
var names = [@(stateNames.map{"\"" + _ + "\""}.mkString(","))];
There are a number of different options that you can uses here.
Option 1, you would need to create a class like below
package ext;
import play.templates.JavaExtensions;
import java.util.*;
public class MyExtensions extends JavaExtensions {
public static String stringifyList(List list) {
StringBuffer buff = new StringBuffer();
for (Object item: list) {
buff.append("'"+item.toString()+"'"+",");
}
return buff.toString();
}
}
You would then just use this by using the JavaExtension in your view, so
var names=[${list.stringifyList()}];
Options 2 and 3 are detailed below
<script type="text/javascript">
// option 2
var names = new Array();
#{list items:list, as:'item'}
names.push('${item}');
#{/list}
// option 3
var names2 = [%{
for (String item: list) {
out.print("'"+item+"'"+",");
}
}%]
</script>
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.