Skip to content

Commit

Permalink
- Change the type of templatesTypes sbt key to Map[String, String] (t…
Browse files Browse the repository at this point in the history
…he template result type can be retrieved using a type member of the format)

- Add some API documentation to play.templates public API
- Include play-templates Scaladoc
- Document how to support a custom template format
  • Loading branch information
julienrf committed Apr 8, 2013
1 parent acacd23 commit 75f0f52
Show file tree
Hide file tree
Showing 15 changed files with 180 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Adding support for a custom format to the template engine

The built-in template engine supports common template formats (HTML, XML, etc.) but you can easily add support for your own formats, if needed. This page summarizes the steps to follow to support a custom format.

## Overview of the the templating process

The template engine builds its result by appending static and dynamic content parts of a template. Consider for instance the following template:

```
foo @bar baz
```

It consists in two static parts (`foo ` and ` baz`) around one dynamic part (`bar`). The template engine concatenates these parts together to build its result. Actually, in order to prevent cross-site scripting attacks, the value of `bar` can be escaped before being concatenated to the rest of the result. This escaping process is specific to each format: e.g. in the case of HTML you want to transform “<” into “&amp;lt;”.

How does the template engine know which format correspond to a template file? It looks at its extension: e.g. if it ends with `.scala.html` it associates the HTML format to the file.

In summary, to support your own template format you need to perform the following steps:

* Implement the text integration process for the format ;
* Associate a file extension to the format.

## Implement a format

Implement the `play.templates.Format<A>` interface that has the methods `A raw(String text)` and `A escape(String text)` that will be used to integrate static and dynamic template parts, respectively.

The type parameter `A` of the format defines the result type of the template rendering, e.g. `Html` for a HTML template. This type must be a subtype of the `play.templates.Appendable<A>` trait that defines how to concatenates parts together.

For convenience, Play provides a `play.api.templates.BufferedContent<A>` abstract class that implements `play.templates.Appendable<A>` using a `StringBuilder` to build its result and that implements the `play.mvc.Content` interface so Play knows how to serialize it as an HTTP response body.

In short, you need to write to classes: one defining the result (implementing `play.templates.Appendable<A>`) and one defining the text integration process (implementing `play.templates.Format<A>`). For instance, here is how the HTML format could be defined:

```java
public class Html extends BufferedContent<Html> {
public Html(StringBuilder buffer) {
super(buffer);
}
String contentType() {
return "text/html";
}
}

public class HtmlFormat implements Format<Html> {
Html raw(String text: String) { … }
Html escape(String text) { … }
public static final HtmlFormat instance = new HtmlFormat(); // The build process needs a static reference to the format (see the next section)
}
```

## Associate a file extension to the format

The templates are compiled into a `.scala` files by the build process just before compiling the whole application sources. The `sbt.PlayKeys.templatesTypes` key is a sbt setting of type `Map[String, String]` defining the mapping between file extensions and template formats. For instance, if you want Play to use your onw HTML format implementation you have to write the following in your build file to associate the `.scala.html` files to your custom `my.HtmlFormat` format:

```scala
templatesTypes += ("html" -> "my.HtmlFormat.instance")
```

Note that the right side of the arrow contains the fully qualified name of a static value of type `play.templates.Format<?>`.

> **Next:** [[HTTP form submission and validation | JavaForms]]
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ Again, there’s nothing special here. You can just call any other template you
```

## moreScripts and moreStyles equivalents

> **Next:** [[HTTP form submission and validation | ScalaForms]]
To define old moreScripts or moreStyles variables equivalents (like on Play! 1.x) on a Scala template, you can define a variable in the main template like this :

```html
Expand Down Expand Up @@ -183,4 +183,4 @@ And on an extended template that not need an extra script, just like this :
}
```

> **Next:** [[HTTP form submission and validation | JavaForms]]
> **Next:** [[Custom formats | JavaCustomTemplateFormat]]
1 change: 1 addition & 0 deletions documentation/manual/javaGuide/main/templates/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- [[Templates syntax | JavaTemplates]]
- [[Common use cases | JavaTemplateUseCases]]
- [[Custom formats | JavaCustomTemplateFormat]]

### Main concepts

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Adding support for a custom format to the template engine

The built-in template engine supports common template formats (HTML, XML, etc.) but you can easily add support for your own formats, if needed. This page summarizes the steps to follow to support a custom format.

## Overview of the the templating process

The template engine builds its result by appending static and dynamic content parts of a template. Consider for instance the following template:

```
foo @bar baz
```

It consists in two static parts (`foo ` and ` baz`) around one dynamic part (`bar`). The template engine concatenates these parts together to build its result. Actually, in order to prevent cross-site scripting attacks, the value of `bar` can be escaped before being concatenated to the rest of the result. This escaping process is specific to each format: e.g. in the case of HTML you want to transform “<” into “&amp;lt;”.

How does the template engine know which format correspond to a template file? It looks at its extension: e.g. if it ends with `.scala.html` it associates the HTML format to the file.

Finally, you usually want your template files to be used as the body of your HTTP responses, so you have to define how to make a Play result from a template rendering result.

In summary, to support your own template format you need to perform the following steps:

* Implement the text integration process for the format ;
* Associate a file extension to the format ;
* Eventually tell Play how to send the result of a template rendering as an HTTP response body.

## Implement a format

Implement the `play.templates.Format[A]` trait that has the methods `raw(text: String): A` and `escape(text: String): A` that will be used to integrate static and dynamic template parts, respectively.

The type parameter `A` of the format defines the result type of the template rendering, e.g. `Html` for a HTML template. This type must be a subtype of the `play.templates.Appendable[A]` trait that defines how to concatenates parts together.

For convenience, Play provides a `play.api.templates.BufferedContent[A]` abstract class that implements `play.templates.Appendable[A]` using a `StringBuilder` to build its result and that implements the `play.api.mvc.Content` trait so Play knows how to serialize it as an HTTP response body (see the last section of this page for details).

In short, you need to write to classes: one defining the result (implementing `play.templates.Appendable[A]`) and one defining the text integration process (implementing `play.templates.Format[A]`). For instance, here is how the HTML format is defined:

```scala
// The `Html` result type. We extend `BufferedContent[Html]` rather than just `Appendable[Html]` so
// Play knows how to make an HTTP result from a `Html` value
class Html(buffer: StringBuilder) extends BufferedContent[Html](buffer) {
val contentType = MimeTypes.HTML
}

object HtmlFormat extends Format[Html] {
def raw(text: String): Html =
def escape(text: String): Html =
}
```

## Associate a file extension to the format

The templates are compiled into a `.scala` files by the build process just before compiling the whole application sources. The `sbt.PlayKeys.templatesTypes` key is a sbt setting of type `Map[String, String]` defining the mapping between file extensions and template formats. For instance, if HTML was not supported out of the box by Play, you would have to write the following in your build file to associate the `.scala.html` files to the `play.api.templates.HtmlFormat` format:

```scala
templatesTypes += ("html" -> "play.api.templates.HtmlFormat")
```

Note that the right side of the arrow contains the fully qualified name of a value of type `play.templates.Format[_]`.

## Tell Play how to make an HTTP result from a template result type

Play can write an HTTP response body for any value of type `A` for which it exists an implicit `play.api.http.Writeable[A]` value. So all you need is to define such a value for your template result type. For instance, here is how to define such a value for HTTP:

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

> **Note:** if your template result type extends `play.api.templates.BufferedContent` you only need to define an
> implicit `play.api.http.ContentTypeOf` value:
> ```scala
> implicit def contentTypeHttp(implicit codec: Codec): ContentTypeOf[Http] =
> ContentTypeOf[Http](Some(ContentTypes.HTTP))
> ```
> **Next:** [[HTTP form submission and validation | ScalaForms]]
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,4 @@ And on an extended template that not need an extra script, just like this :

}
```
> **Next:** [[HTTP form submission and validation | ScalaForms]]
> **Next:** [[Custom format | ScalaCustomTemplateFormat]]
1 change: 1 addition & 0 deletions documentation/manual/scalaGuide/main/templates/_Sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- [[Scala templates syntax | ScalaTemplates]]
- [[Common use cases | ScalaTemplateUseCases]]
- [[Custom format | ScalaCustomTemplateFormat]]

### Main concepts

Expand Down
7 changes: 4 additions & 3 deletions framework/project/Tasks.scala
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ object Tasks {
(file("src/anorm/src/main/scala") ** "*.scala").get ++
(file("src/play-filters-helpers/src/main/scala") ** "*.scala").get ++
(file("src/play-jdbc/src/main/scala") ** "*.scala").get ++
(file("src/play/target/scala-" + sbv + "/src_managed/main/views/html/helper") ** "*.scala").get
(file("src/play/target/scala-" + sbv + "/src_managed/main/views/html/helper") ** "*.scala").get ++
(file("src/templates/src/main/scala") ** "*.scala").get
val options = Seq("-sourcepath", base.getAbsolutePath, "-doc-source-url", "https://github.com/playframework/Play20/tree/" + BuildSettings.buildVersion + "/framework€{FILE_PATH}.scala")
new Scaladoc(10, cs.scalac)("Play " + BuildSettings.buildVersion + " Scala API", sourceFiles, classpath.map(_.data) ++ allJars, file("../documentation/api/scala"), options, s.log)

Expand Down Expand Up @@ -192,9 +193,9 @@ object Tasks {

(sourceDirectory ** "*.scala.html").get.foreach {
template =>
val compile = compiler.getDeclaredMethod("compile", classOf[java.io.File], classOf[java.io.File], classOf[java.io.File], classOf[String], classOf[String], classOf[String])
val compile = compiler.getDeclaredMethod("compile", classOf[java.io.File], classOf[java.io.File], classOf[java.io.File], classOf[String], classOf[String])
try {
compile.invoke(null, template, sourceDirectory, generatedDir, "play.api.templates.Html", "play.api.templates.HtmlFormat", "import play.api.templates._\nimport play.api.templates.PlayMagic._")
compile.invoke(null, template, sourceDirectory, generatedDir, "play.api.templates.HtmlFormat", "import play.api.templates._\nimport play.api.templates.PlayMagic._")
} catch {
case e: java.lang.reflect.InvocationTargetException => {
streams.log.error("Compilation failed for %s".format(template))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import play.api.mvc._
import play.templates._
import play.api.http.MimeTypes

// TODO Derive ContentTypeOf instances from any Content

/**
* Appendable content using a StringBuilder.
Expand Down
11 changes: 5 additions & 6 deletions framework/src/sbt-plugin/src/main/scala/PlayCommands.scala
Original file line number Diff line number Diff line change
Expand Up @@ -295,25 +295,24 @@ exec java $* -cp $classpath """ + customFileName.map(fn => "-Dconfig.file=`dirna

}

val ScalaTemplates = (state: State, sourceDirectory: File, generatedDir: File, templateTypes: PartialFunction[String, (String, String)], additionalImports: Seq[String]) => {
val ScalaTemplates = (state: State, sourceDirectory: File, generatedDir: File, templateTypes: Map[String, String], additionalImports: Seq[String]) => {
import play.templates._

val templateExt: PartialFunction[File, (File, String, String, String)] = {
case p if templateTypes.isDefinedAt(p.name.split('.').last) =>
val templateExt: PartialFunction[File, (File, String, String)] = {
case p if templateTypes.contains(p.name.split('.').last) =>
val extension = p.name.split('.').last
val exts = templateTypes(extension)
(p, extension, exts._1, exts._2)
(p, extension, exts)
}
(generatedDir ** "*.template.scala").get.map(GeneratedSource(_)).foreach(_.sync())
try {

(sourceDirectory ** "*.scala.*").get.collect(templateExt).foreach {
case (template, extension, t, format) =>
case (template, extension, format) =>
ScalaTemplateCompiler.compile(
template,
sourceDirectory,
generatedDir,
t,
format,
additionalImports.map("import " + _.replace("%format%", extension)).mkString("\n"))
}
Expand Down
2 changes: 1 addition & 1 deletion framework/src/sbt-plugin/src/main/scala/PlayKeys.scala
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ trait PlayKeys {

val ebeanEnabled = SettingKey[Boolean]("play-ebean-enabled")

val templatesTypes = SettingKey[PartialFunction[String, (String, String)]]("play-templates-formats")
val templatesTypes = SettingKey[Map[String, String]]("play-templates-formats")

val closureCompilerOptions = SettingKey[Seq[String]]("play-closure-compiler-options")

Expand Down
13 changes: 7 additions & 6 deletions framework/src/sbt-plugin/src/main/scala/PlaySettings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,14 @@ trait PlaySettings {

templatesImport := Seq("play.api.templates._", "play.api.templates.PlayMagic._"),

templatesTypes := {
case "html" => ("play.api.templates.Html", "play.api.templates.HtmlFormat")
case "txt" => ("play.api.templates.Txt", "play.api.templates.TxtFormat")
case "xml" => ("play.api.templates.Xml", "play.api.templates.XmlFormat")
},

scalaIdePlay2Prefs <<= (state, thisProjectRef, baseDirectory) map { (s, r, baseDir) => saveScalaIdePlay2Prefs(r, Project structure s, baseDir) }
scalaIdePlay2Prefs <<= (state, thisProjectRef, baseDirectory) map { (s, r, baseDir) => saveScalaIdePlay2Prefs(r, Project structure s, baseDir) },

templatesTypes := Map(
"html" -> "play.api.templates.HtmlFormat",
"txt" -> "play.api.templates.TxtFormat",
"xml" -> "play.api.templates.XmlFormat"
)

)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ package play.templates {
case class Block(whitespace: String, args: Option[PosString], content: Seq[TemplateTree]) extends ScalaExpPart with Positional
case class Value(ident: PosString, block: Block) extends Positional

def compile(source: File, sourceDirectory: File, generatedDirectory: File, resultType: String, formatterType: String, additionalImports: String = "") = {
def compile(source: File, sourceDirectory: File, generatedDirectory: File, formatterType: String, additionalImports: String = "") = {
val resultType = formatterType + ".Appendable"
val (templateName, generatedSource) = generatedFile(source, sourceDirectory, generatedDirectory)
if (generatedSource.needRecompilation) {
val generated = parseAndGenerateCode(templateName, Path(source).byteArray, source.getAbsolutePath, resultType, formatterType, additionalImports)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// TODO Get rid of this file which just demonstrates how harmful copy-pasting is.

package play.api.templates {

trait Template0[Result] { def render(): Result }
Expand Down Expand Up @@ -35,6 +37,7 @@ package play.templates {
}

trait Format[T <: Appendable[T]] {
type Appendable = T
def raw(text: String): T
def escape(text: String): T
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ object Helper {

def compile[T](templateName: String, className: String): T = {
val templateFile = new File(sourceDir, templateName)
val Some(generated) = templateCompiler.compile(templateFile, sourceDir, generatedDir, "play.templates.test.Helper.Html", "play.templates.test.Helper.HtmlFormat")
val Some(generated) = templateCompiler.compile(templateFile, sourceDir, generatedDir, "play.templates.test.Helper.HtmlFormat")

val mapper = GeneratedSource(generated)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,32 @@ package play.templates {

import reflect.ClassTag

/**
* A type that has a binary `+=` operation.
*/
trait Appendable[T] {
def +=(other: T): T
override def equals(x: Any): Boolean = super.equals(x)
override def equals(x: Any): Boolean = super.equals(x) // FIXME Why do we need these overrides?
override def hashCode() = super.hashCode()
}

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

Expand Down

0 comments on commit 75f0f52

Please sign in to comment.