

§The template engine

§A type safe template engine based on Scala

Play comes with Twirl, a powerful Scala-based template engine, whose design was inspired by ASP.NET Razor. Specifically it is:










For example, here is a simple template:



@for(order <- orders) {


Content html = views.html.Application.index.render(customer, orders);

§Syntax: the magic ‘@’ character


Hello @customer.getName()!
          Dynamic code


Hello @(customer.getFirstName() + customer.getLastName())!
                          Dynamic Code

Note: Make sure not to include whitespaces between keywords of dynamic statements and parentheses.

For example, the following code doesn’t work:

@for (menu <- menuList) { ... }  // Compilation error: '(' expected but ')' found.


                                  Dynamic Code


My email is [email protected]

§Template parameters



You can also use default values for parameters:

@(title: String = "Home")

Or even several parameter groups:

@(title:String)(body: Html)

§Template constructor

By default, a template is generated as a static function that can be invoked in any context. If your template has dependencies on components, such as the messages API, you may find it easier to inject it with the components (and other templates) that it needs, and then you can inject that template into the controllers that use it.

Twirl supports declaring a constructor for templates, using @this() syntax at the start of the file, before the template parameters. The arguments to the constructor can be defined in the same way as the template parameters:

@this(messagesApi: MessagesApi)




@for(p <- products) {




@if(items.isEmpty()) {
  <h1>Nothing to display</h1>
} else {

§Declaring reusable blocks

You can create reusable code blocks:

@display(product: models.Product) = {
  @product.getName() ([email protected]())

@for(product <- products) {

Note that you can also declare reusable pure code blocks:

@title(text: String) = @{




@implicitFieldConstructor = @{ MyFieldConstructor() }

§Declaring reusable values

You can define scoped values using the defining helper:

  <div>Hello @fullName</div>

§Import statements



@import utils._





TwirlKeys.templateImports += ""



 * This is a comment *


 * Home page.                        *
 *                                   *
 * @param msg The message to display *
@(msg: String)




Note: When using this feature, consider the security implications of outputting raw HTML if there is any possibility that the user can control the content. This technique is a common cause of Cross Site Scripting (XSS) vulnerabilities and is dangerous if not used with caution.

For example to output raw HTML:


Next: Dependency Injection with Templates
