Scala Play 2.4视图渲染vs应用

Ziz*_*Tai 3 scala playframework playframework-2.0

我注意到这两个views.html.myView.render(...),views.html.myView(...)可以用来从模板生成一个页面.但是,如果我们需要将隐式参数列表传递到视图中,则似乎只有apply版本在render版本不编译时才有效.

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

Mic*_*jac 5

render方法旨在从Java中使用,并且apply旨在从Scala中使用.渲染代表apply,除非有多个参数列表(来自currying或implicits),否则它们将具有完全相同的签名.

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

@(message: String)(implicit i: Int)
Run Code Online (Sandbox Code Playgroud)

它将被编译为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)
Run Code Online (Sandbox Code Playgroud)

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

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

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

def render(message:String): play.twirl.api.HtmlFormat.Appendable = apply(message)
Run Code Online (Sandbox Code Playgroud)