Rumata Estorsky
Rumata Estorsky

Reputation: 55

Play Scala Custom Template Format

I want to use Play Templates to generate source code for a programming language.

I'd like to add support for a custom format to the template engine as per Play's documentation. But I do not understand:

1) Where to specify a new file extension? templatesTypes += ("code" -> "some.lang.LangFormat") in build.sbt?

2) how to stop Play from escaping HTML characters and adding blank lines

Has anyone got experience with Play custom template formats? If possible please provide links to examples.

Upvotes: 1

Views: 350

Answers (1)

James Roper
James Roper

Reputation: 12850

1) The extension in your example would "code", so for example, for a python template generator, you would do:

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

2) The thing that escapes HTML characters is the some.lang.LangFormat class, which has to implement the play.api.template.Format class. This has the following two methods:

/**
 * 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
}

So you can just make escape delegate to raw if you don't want to do any escaping.

As far as controlling line breaks goes, this is an aspect of the templates themselves, if you put line breaks in a template, they will appear in the result. So for example:

@if(foo) {
  @bar
}

Will have line breaks, whereas:

@if(foo) {@bar}

won't.

Upvotes: 3

Related Questions