【问题标题】:Play Scala Custom Template Format播放 Scala 自定义模板格式
【发布时间】:2013-12-03 19:17:49
【问题描述】:

我想使用 Play Templates 生成编程语言的源代码。

我想根据Play's documentation 向模板引擎添加对自定义格式的支持。但我不明白:

1) 在哪里指定新的文件扩展名? templatesTypes += ("code" -> "some.lang.LangFormat") 在 build.sbt 中?

2) 如何阻止 Play 转义 HTML 字符和添加空行

有人有使用 Play 自定义模板格式的经验吗? 如果可能,请提供示例链接。

【问题讨论】:

    标签: scala templates playframework playframework-2.0 sbt


    【解决方案1】:

    1) 您示例中的扩展将“编码”,例如,对于 python 模板生成器,您可以:

    templateTypes += ("py" -> "some.python.PythonFormat")
    

    2) 转义 HTML 字符的是 some.lang.LangFormat 类,它必须实现 play.api.template.Format 类。这有以下两种方法:

    /**
     * A template format defines how to properly integrate content for a type `T` (e.g. to prevent cross-site scripting attacks)
     * @tparam T The underlying type that this format applies to.
     */
    trait Format[T <: Appendable[T]] {
      type Appendable = T
    
      /**
       * Integrate `text` without performing any escaping process.
       * @param text Text to integrate
       */
      def raw(text: String): T
    
      /**
       * Integrate `text` after escaping special characters. e.g. for HTML, “<” becomes “&amp;lt;”
       * @param text Text to integrate
       */
      def escape(text: String): T
    }
    

    因此,如果您不想进行任何转义,则可以将 escape 委托给 raw

    就控制换行而言,这是模板本身的一个方面,如果您在模板中放置换行符,它们将出现在结果中。比如:

    @if(foo) {
      @bar
    }
    

    会有换行符,而:

    @if(foo) {@bar}
    

    不会。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 2013-05-10
      • 2023-04-06
      相关资源
      最近更新 更多