在Play 2.5中创建自定义模板格式

时间:2017-07-03 22:21:25

标签: scala model-view-controller types playframework customization

我正在尝试按照Play documentation制作自定义模板格式(在 播放2.5_& _Scala 2.11.11 中)但是我在这里,这意味着它不适合我。

我希望新模板的文件扩展名为“ stream ”(如this video中现在已有几年了)所以我根据文档建议创建了此文件:

   package ui

   import akka.NotUsed
   import akka.stream.scaladsl.{Source}
   import play.twirl.api._

   import scala.collection.immutable

   case class HtmlStream(source: Source[Html, NotUsed]) extends Appendable[HtmlStream] {

     def +=(other: HtmlStream): HtmlStream = andThen(other)
     def andThen(other: HtmlStream): HtmlStream = HtmlStream(source.merge(other.source))

   }

   object HtmlStream {

     def apply(text: String): HtmlStream = apply(Html(text))
     def apply(html: Html): HtmlStream = HtmlStream(Source.single(html))

   }

   object HtmlStreamFormat extends Format[HtmlStream] {

     def raw(text: String): HtmlStream = HtmlStream(text)
     def escape(text: String): HtmlStream = raw(HtmlFormat.escape(text).body)

     override def empty: HtmlStream = ???
     override def fill(elements: immutable.Seq[HtmlStream]): HtmlStream = ???

   }

并将其添加到 build.sbt 文件中:

   TwirlKeys.templateFormats += ("stream" -> "ui.HtmlStreamFormat.instance")

我无法在底部看到包含以下内容的隐藏位置(在前面提到的 Play documentation 上);可能是这个问题:

  

Play可以为任何类型A的值编写HTTP响应正文   它存在一个隐含的play.api.http.Writeable [A]值。所有你   需要是为模​​板结果类型定义这样的值。对于   例如,以下是如何为HTTP定义这样的值:

   implicit def writableHttp(implicit codec: Codec): Writeable[Http] =
  Writeable[Http](result => codec.encode(result.body), Some(ContentTypes.HTTP))

当我尝试创建新的view文件时,例如叫test.scala.stream,它不知道应该是什么类型,所以看起来肯定是错的。这个需要帮助!

2 个答案:

答案 0 :(得分:0)

所以我已经破解了这个,并且在社区精神中就是这样。

1)创建一个文件(我称之为" HtmlStream "因为我希望流式传输HTML):

   package ui

   import akka.NotUsed
   import akka.stream.scaladsl.{Source}
   import play.twirl.api._

   import scala.collection.immutable
   import scala.concurrent.ExecutionContext

   case class HtmlStream(source: Source[Html, NotUsed]) extends Appendable[HtmlStream] {

     def +=(other: HtmlStream): HtmlStream = andThen(other)
     def andThen(other: HtmlStream): HtmlStream = HtmlStream(source.merge(other.source))

   }

   object HtmlStream {

     def apply(text: String): HtmlStream = apply(Html(text))
     def apply(html: Html): HtmlStream = HtmlStream(Source.single(html))

   }

   object HtmlStreamFormat extends Format[HtmlStream] {

     def raw(text: String): HtmlStream = HtmlStream(text)
     def escape(text: String): HtmlStream = raw(HtmlFormat.escape(text).body)

     override def empty: HtmlStream = raw("")
     override def fill(elements: immutable.Seq[HtmlStream]): HtmlStream = elements.reduce((agg, curr) => agg.andThen(curr))

   }

   object HtmlStreamImplicits {

      implicit def toSource(stream: HtmlStream)(implicit ec: ExecutionContext): Source[Html, NotUsed] = {
      stream.source.filter(_.body.nonEmpty)

   }

2)我将这些行添加到 build.sbt 文件中:

   TwirlKeys.templateFormats += ("stream" -> "ui.HtmlStreamFormat")
   TwirlKeys.templateImports ++= Vector("ui.HtmlStream", "ui.HtmlStream._", "ui.HtmlStreamFormat._", "ui.HtmlStreamImplicits._")

3)我添加了一个名为test1.scala.stream的模板(在提示时使用HTML的文件关联):

   @(body: HtmlStream)

   <!DOCTYPE html>
   <html lang="en">
      <head>
          <title>title</title>
          <link rel="stylesheet" media="screen" href="assets/stylesheets/main.css">
          <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
          <script src="assets/javascripts/hello.js" type="text/javascript"></script>
      </head>
      <body>
      <h1>Streaming the body</h1>

      <div>
          <div>
              @body
          </div>
      </div>
      </body>
   </html>

4)最后,我可以将此模板用作任何其他模板,方法是将其转换为新的 HtmlStream 类型。

  def streamHtml = Action { request =>

    val async1: Future[Result] = rr.getAsync(embed = true)(request) // get future
    val async1Html: Future[Html] = async1.flatMap(x => Pagelet.readBody(x)) // separate function to convert Future[Result] to Future[Html]
    val htmlStream: HtmlStream = HtmlStream(fromFuture(async1Html)) // c onvert to HtmlStream type

    Ok.chunked(views.stream.test1(htmlStream)) // chunk the new data type by sending through new template

  }

希望这对其他人有帮助!

答案 1 :(得分:0)

这是一个自定义格式,我按照播放规范编写了cvs和作品,包括有关ContentTypes.HTTP的问题:

一些建议:

1 - 如果您希望该播放框架可以编写HTTP响应正文,则需要定义正文内容。请查看下面的代码隐式def contentTypeCsv ,这是您必须要做的事情,但在您的特定正文内容中。

2 - 其他重要的建议,带有CUSTOM FORMAT的旋转模板应该在您自定义模板所在的built.sbt中定义,无论项目是单项目还是多项目都无关紧要。

class Csv(buffer: immutable.Seq[Csv],text:String,escape:Boolean) extends BufferedContent[Csv](buffer, text) {

  val contentType = Csv.contentType

  def this(text: String) = this(Nil, Formats.safe(text),false)
  def this(buffer: immutable.Seq[Csv]) = this(buffer, "",false)


  override protected def buildString(builder: StringBuilder) {
    if (elements.nonEmpty) {
      elements.foreach { e =>
        e.buildString(builder)
      }
    } else if (escape) {
      // Using our own algorithm here because commons lang escaping wasn't designed for protecting against XSS, and there
      // don't seem to be any other good generic escaping tools out there.
      text.foreach {
        case '"' => builder.append("\"\"")
        case c => builder += c
      }
    } else {
      builder.append(text)
    }
  }
}


object Csv {
  val contentType = "text/csv"
  implicit def contentTypeCsv(implicit codec: Codec): ContentTypeOf[Csv] = ContentTypeOf[Csv](Some(Csv.contentType))

  def apply(text: String): Csv = new Csv(text)

  def empty: Csv = new Csv("")
}
object CsvFormat extends Format[Csv] {
  def raw(text: String): Csv = Csv(text)
  def escape(text: String): Csv = {
    new Csv(Nil, text, true)
  }

  def empty: Csv = new Csv("")

  def fill(elements: Seq[Csv]): Csv = new Csv(elements)
}