Scala Play 2.4视图渲染vs应用

时间:2015-09-26 11:31:55

标签: scala playframework playframework-2.0

我注意到views.html.myView.render(...)views.html.myView(...)都可用于从模板生成页面。但是,如果我们需要将隐式参数列表传递给视图,则apply版本似乎只有render版本才能正常工作。

我认为views.html.myView.apply可能代表views.html.myView.render(或反过来)幕后,但我不确定,也无法找到与此相关的任何内容。文档。我可以从Twirl文档中得到的唯一一点是TemplateN个特征都定义了render方法,但没有一个提到apply

1 个答案:

答案 0 :(得分:5)

render方法用于Java,apply用于Scala。将代理渲染到apply,他们将拥有完全相同的签名,除非有多个参数列表(来自currying或implicits)。

假设我在play-scala激活器模板中有index.html.scala,修改为添加隐式Int参数:

@(message: String)(implicit i: Int)

它将被编译为target/scala-2.11/twirl/main/views/html/index.template.scala。以下是相关部分:

def apply(message: String)(implicit i: Int): play.twirl.api.HtmlFormat.Appendable = ...

def render(message: String, i: Int): play.twirl.api.HtmlFormat.Appendable =
    apply(message)(i)

render中的参数被压缩成一个列表。由于您不能使用Java(或多个参数列表)中的含义,因此需要在单个列表中显式传递它们。

如果我删除隐含的,它们是相同的:

def apply(message: String): play.twirl.api.HtmlFormat.Appendable = ...

def render(message:String): play.twirl.api.HtmlFormat.Appendable = apply(message)