我假设您希望能够调用Ok(views.Test.build)
. Play 不知道 ScalaTags,所以我们必须自己在这里写一些东西。
Play 使用一些隐式机制来生成 HTTP 响应。当你打电话时Ok(...)
,你实际上是在调用apply
trait play.api.mvc.Results
。我们来看看它的签名:
def apply[C](content: C)(implicit writeable: Writeable[C]): Result
所以我们可以看到我们需要一个隐式Writeable[scalatags.Text.all.Tag]
:
implicit def writeableOfTag(implicit codec: Codec): Writeable[Tag] = {
Writeable(tag => codec.encode("<!DOCTYPE html>\n" + tag.render))
}
不要忘记包含一个 doctype 声明。ScalaTags 没有给你。
对自身的调用Writeable.apply
需要另一个隐式来确定内容类型。这是它的签名:
def apply[A](transform: A => ByteString)(implicit ct: ContentTypeOf[A]): Writeable[A]
所以让我们写一个隐含的ContentTypeOf[Tag]
:
implicit def contentTypeOfTag(implicit codec: Codec): ContentTypeOf[Tag] = {
ContentTypeOf[Tag](Some(ContentTypes.HTML))
}
这允许我们避免必须as("text/html")
显式编写,它包含字符集(由隐式编解码器提供),导致Content-Type
.text/html; charset=utf-8
把它们放在一起:
import play.api.http.{ ContentTypeOf, ContentTypes, Writeable }
import play.api.mvc.Results.Ok
import scalatags.Text.all._
def build: Tag = {
html(
head(
title := "Test"
),
body(
h1("This is a Triumph"),
div(
"Test"
)
)
)
}
implicit def contentTypeOfTag(implicit codec: Codec): ContentTypeOf[Tag] = {
ContentTypeOf[Tag](Some(ContentTypes.HTML))
}
implicit def writeableOfTag(implicit codec: Codec): Writeable[Tag] = {
Writeable(tag => codec.encode("<!DOCTYPE html>\n" + tag.render))
}
def foo = Action { implicit request =>
Ok(build)
}
您可能希望将这些隐式藏在方便的地方,然后将它们导入您的控制器中。