12

我更喜欢使用前者而不是后者,但我不确定如何将 Scalatags 合并到 playframework 中。

这是我的简单布局:

object Test
{
  import scalatags.Text.all._
  def build =
  {

    html(
      head(
        title := "Test"
      ),
      body(

        h1("This is a Triumph"),
        div(
          "Test"
        )
      )
    )
  }
}

这就是我尝试渲染它的方式:

Ok(views.Test.build.render)

问题是,我把它作为一个普通的字符串,而不是作为 HTML。

现在,当然一种解决方案是简单地追加。

Ok(views.Test.build.render).as("text/html")

但这真的是唯一的方法吗?(没有创建一个辅助方法)

4

1 回答 1

17

我假设您希望能够调用Ok(views.Test.build). Play 不知道 ScalaTags,所以我们必须自己在这里写一些东西

Play 使用一些隐式机制来生成 HTTP 响应。当你打电话时Ok(...),你实际上是在调用applytrait 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)
}

您可能希望将这些隐式藏在方便的地方,然后将它们导入您的控制器中。

于 2017-03-20T05:56:43.583 回答