我假设您希望能够致电Ok(views.Test.build)。 Play 不知道 ScalaTags,所以我们将不得不在这里自己编写一些东西。
Play 使用一些隐式机制来生成 HTTP 响应。当您调用 Ok(...) 时,您实际上是在 play.api.mvc.Results 特征上调用 apply。我们来看看它的签名:
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")并且它包含字符集(由隐式编解码器提供),从而产生text/html; charset=utf-8 的Content-Type 标头。
把它们放在一起:
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)
}
您可能希望将这些隐式隐藏在方便的地方,然后将它们导入您的控制器中。