scala 在 Play Framework 2.0 模板中使用选项助手

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10127156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:05:38  来源:igfitidea点击:

Use of option helper in Play Framework 2.0 templates

scalaplayframework-2.0

提问by UltraMaster

I'm trying to use views.html.helper.select(documentation here). I don't know scala, so i'm using java. I need to pass object of type Seq[(String)(String)] to the template right? Something like:

我正在尝试使用views.html.helper.select此处的文档)。我不知道 Scala,所以我使用的是 java。我需要将 Seq[(String)(String)] 类型的对象传递给模板,对吗?就像是:

@(fooForm:Form[Foo])(optionValues:Seq[(String)(String)])

@import helper._

@form(routes.foo){
  @select(field=myForm("selectField"),options=optionValues)
}

I don't know how to create Seq[(String)(String)] in java. I need to fill this collection with pairs (id,title) from my enum class.

我不知道如何在 java 中创建 Seq[(String)(String)]。我需要用我的枚举类中的对 (id,title) 填充这个集合。

Can somebody show me some expample how to use the select helper?

有人可以告诉我一些如何使用选择助手的示例吗?

I found thisthread on users group, but Kevin's answer didn't helped me a lot.

我在用户组上找到了这个线程,但凯文的回答对我没有多大帮助。

回答by Julien Richard-Foy

The right type is: Seq[(String, String)]. It means a sequence of pairs of String. In Scala there is a way to define pairs using the arrow: a->b == (a, b). So you could write e.g.:

正确的类型是:Seq[(String, String)]。它表示字符串对的序列。在 Scala 中有一种使用箭头定义对的方法:a->b == (a, b)。所以你可以写例如:

@select(field = myForm("selectField"), options = Seq("foo"->"Foo", "bar"->"Bar"))

But there is another helper, as shown in the documentation, to build the sequence of select options: options, so you can rewrite the above code as:

但是还有另一个帮助程序,如文档中所示,用于构建选择选项的序列:options,因此您可以将上述代码重写为:

@select(myForm("selectField"), options("foo"->"Foo", "bar"->"Bar"))

In the case your options values are the same as their label, you can even shorten the code to:

如果您的选项值与其标签相同,您甚至可以将代码缩短为:

@select(myForm("selectField"), options(List("Foo", "Bar")))

(note: in Play 2.0.4 options(List("Foo", "Bar"))doesn't compile, so you can try this options(Seq("Foo", "Bar")))

(注意:在 Play 2.0.4options(List("Foo", "Bar"))中不能编译,所以你可以试试这个options(Seq("Foo", "Bar"))

To fill the options from Java code, the more convenient way is to use either the overloaded optionsfunction taking a java.util.List<String>as parameter (in this cases options values will be the same as their label) or the overloaded function taking a java.util.Map<String, String>.

要从 Java 代码填充选项,更方便的方法是使用options以 ajava.util.List<String>作为参数的重载函数(在这种情况下,选项值将与其标签相同)或使用java.util.Map<String, String>.