[英]Assigning String array to js variable for autocomplete in play?
I have a js variable in the index.html file and i want to do an assignment like this: 我在index.html文件中有一个js变量,我想做一个像这样的赋值:
var names=["${stateNames}"];
where stateNames is a Java List containing state names. 其中stateNames是包含州名的Java List。 How do i do an assignment like the above so that names now has all the state names contained in stateNames ? 我如何进行如上所述的赋值,以便名称现在包含stateNames中包含的所有州名? The variable stateNames is passed to index.html from the play controller. 变量stateNames从播放控制器传递给index.html。
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 : 如果您使用的是Groovy模板,这很简单,因为您可以访问Groovy的集合方法 :
var names=[${stateNames.collect{'"'+it+'"'}.join(",")}];
collect
transforms your collection, join
creates one big String separated by the given String. collect
转换您的集合, join
创建一个由给定String分隔的大字符串。
Scala version for completeness' sake: Scala版本为了完整性的缘故:
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 选项1,您需要创建如下所示的类
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 然后,您可以在视图中使用JavaExtension来使用它,所以
var names=[${list.stringifyList()}];
Options 2 and 3 are detailed below 选项2和3详述如下
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.