私はあなたが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")
明示的とそれが文字セット(暗黙のコーデックの礼儀)を含んを書くことを避けることができますその結果、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)
}
は、おそらくどこかに便利なものを暗黙に押し込むと、あなたのコントローラ(複数可)でそれらをインポートしたいです。
なぜtwirlがデフォルトのテンプレートエンジンであるのですか?スカタタグはより簡単に見える。 – BlueSky