Twirl is a Scala-based HTML template engine.

Overview

Twirl can generate any text-based format, such as HTML, XML or CVS. Templates are compiled as Scala objects that are named with a pattern of views.html.path.filename. The object defines an apply method that takes the parameters of the Twirl template.

The Magic Charactor

The Scala template uses @ as the magic character that indicates the beginning of a dynamic statement. Because the end of the dynamic statement will be inferred from the code, the syntax only supports simple statements. If you use a multi-token statement, put them inside a pair of parentheses. Also don’t have a whitespace between a keyword and the next parentheses. Use curly brackets to write multi-statement block. Common syntaxes are:

  • Escaping @: @@
  • Iterating: @for(){}
  • If-block: @if() {} else {}
  • Reusable block: @name(p1: T1) = {}
  • Scoped value: `@defining(statement) { value => … }
  • Import statements: @import ... after the declaration of template parameters
  • Comments: @* *@
  • Raw HTML: @Html(content)

Template Parameters and Constructor

A template is like an apply metehod, the parameters are defined at the top of the template file such as @(p1: T1, p2: T2).

A template can have a constructor to declare dependent components or templates. Using @this(d1: T1, d2: T2) before the template parameters to define a constructor. This will make the Twirl to generate a class rather than a static object for the template. You can inject the class into a controller.

Render Values

Twirl use toString method of an object. If values are insdie Option or collections (Seq, Array, TraversableOnce), Twirl unwraps the values and calls toString.

Templating Process

The templating process has three steps: text format, association of text format and file extension, sending formatted as an HTTP response body.