简体   繁体   English

在play framework 2.0中为java列表分配变量

[英]Assigning variable to java list in play framework 2.0

I need to access a Java list from html code in play. 我需要从播放的html代码中访问Java列表。 My list is returned by a public static method: 我的列表由公共静态方法返回:

ComboboxOpts.getListOfValues()

I am using this method several times in my scala code want to assign it to some variable. 我在我的scala代码中多次使用此方法想要将其分配给某个变量。 Maybe something similar to this 也许类似的东西

@mylist = ComboboxOpts.getListOfValues()

So that I can use it like this 所以我可以像这样使用它

@for(i <- 0 to mylist.size -1){
    //Do stuff
}

rather than this 而不是这个

@for(i <- 0 to ComboboxOpts.getListOfValues.size -1){
    //Do stuff
}

You can use defining() to set new variables, such as: 您可以使用defining()来设置新变量,例如:

@defining(getName() + " " + getType()) { text => 
  Hello @text!
}

However, for your case, you can just iterate over a list as follows: 但是,对于您的情况,您可以按如下方式迭代列表:

@for(value <- ComboboxOpts.getListOfValues()) {
  <li>@value</li>
} 

This will not call your function repeatedly, and is much more expressive. 这不会重复调用您的函数,而且更具表现力。 The Play documentation has several related examples: http://www.playframework.org/documentation/2.0/JavaTemplates Play文档有几个相关的例子: http//www.playframework.org/documentation/2.0/JavaTemplates

If you absolutely need the index as well, try using Scala's zipWithIndex() . 如果您也完全需要索引,请尝试使用Scala的zipWithIndex()

    Application.java file Application.java文件
  1. public class Application extends Controller { public class Application extends Controller {
  2. public static Result index() { public static Result index(){
  3. List myList = new ArrayList(); 列出myList = new ArrayList();
  4. myList.add("one"); myList.add( “1”);
  5. myList.add("two"); myList.add( “二”);
  6. return ok(index.render(myList)); return ok(index.render(myList));
  7. } }
  8. } }
  9. index.scala.html file index.scala.html文件
  10. @(myList: List[String]) @(myList:List [String])
  11. @main("Welcome to Play 2.0") { @main(“欢迎使用Play 2.0”){
  12. @for(item @for(项目
  13. @item @项目
  14. } }
  15. } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM