Skip to content
javahacks.dev
Play Framework

How to Use Play Twirl Templates for Type Safe HTML Views

Write Twirl templates for a Play application, with typed parameters, loops, conditions, layouts and reusable partials, and see how they compile to Java.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the HTML5, Spring, Gradle, Apache Maven and JUnit5 logos.

Play's default templating language is Twirl. A Twirl template is a file that looks like HTML with a few @ expressions, and it compiles to a Scala class with a render method. That makes it type-safe: the parameters are typed, a call with the wrong argument is a compile error, and a typo in a field name stops the build instead of printing an empty string on a page. This post covers the template as a function, expressions and logic, escaping, layouts, reverse routing and partials, with Play 3 and Java controllers on JDK 25. If you are new to the framework, the Play tutorial comes first.

A template is a function

A template lives under app/views, with a name that ends in .scala.html. Its first line declares the parameters, like a method signature:

app/views/orders/show.scala.htmlHTML
@(order: models.Order, canCancel: Boolean)

<h1>Order @order.getNumber()</h1>
<p>Placed by @order.getCustomer().getName()</p>
<p>Total: @order.getTotal()</p>

@if(canCancel) {
  <a href="@routes.OrderController.cancel(order.getId)">Cancel this order</a>
}

The build compiles this into views.html.orders.show, a class with a render(order, canCancel) method (and apply, so you call it like a function). A Java controller renders it:

app/controllers/OrderController.javajava
public Result show(Long id) {
    Order order = orders.find(id);
    return ok(views.html.orders.show.render(order, order.isCancellable()));
}

Pass the wrong type, or forget an argument, and the project fails to compile with the file and line. That is the benefit over string-based template engines, where the same mistake shows up when a user opens the page. The price is that templates are Scala code underneath, so some syntax is Scala's, and that sbt recompiles them when they change. In development mode, Play recompiles on the next request, and a syntax error appears in the browser with the failing line highlighted.

Parameters can have default values (@(title: String = "Shop")), and implicit parameters (@(order: Order)(implicit request: Http.Request)) give access to the current request without passing it around, which is how CSRF tokens and flash messages reach the template.

Expressions and logic

Everything after @ is an expression, and the parser decides where it ends: at the first character that cannot be part of it.

HTML
<p>@order.getCustomer().getName()</p>
<p>@(order.getTotal() * 2)</p>
<p>Items: @order.getLines().size</p>

Use parentheses when the expression includes operators or when the next character would be parsed as part of it: @(count)px, because @countpx refers to a variable countpx. A literal @ is written @@, which matters for email addresses in templates.

Control structures are written with braces:

HTML
<ul>
@for(line <- order.getLines()) {
  <li>@line.getSku() x @line.getQuantity()</li>
}
</ul>

@if(order.getLines().isEmpty()) {
  <p>No lines.</p>
} else {
  <p>@order.getLines().size lines</p>
}

@defining(order.getTotal()) { total =>
  <p>Total with tax: @(total * 1.2)</p>
}

@for iterates over Java collections when the Java-friendly converters are in scope (Play adds them for Java templates); @defining gives a name to a value you use twice. Keep logic in templates thin. A condition with three parts, or any computation, belongs in the controller or a view model, where it can be tested. A template is a place for presentation.

Escaping

Twirl escapes output by default for the template type. In an .html template, @order.getCustomer().getName() turns <script> into &lt;script&gt;, which is what protects against stored and reflected cross-site scripting. To output raw HTML you must say so explicitly:

HTML
@Html(article.getBodyHtml())

Every use of Html(...) is a decision that the content is already safe. Do it only for HTML you produced and sanitised, never for text a user typed. The escaping context is HTML only: values placed inside a <script> block, an inline onclick attribute or a URL need the escaping for that context, so build such data with JSON serialisation or leave it out of inline script. The rules are in preventing XSS.

A shared layout

Because a template is a function, a layout is a template that takes content as a parameter:

app/views/main.scala.htmlHTML
@(title: String)(content: Html)

<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
    <link rel="stylesheet" href="@routes.Assets.versioned("stylesheets/main.css")">
  </head>
  <body>
    <nav>...</nav>
    <main>@content</main>
  </body>
</html>
app/views/orders/show.scala.htmlHTML
@(order: models.Order)

@main("Order " + order.getNumber()) {
  <h1>Order @order.getNumber()</h1>
}

The second parameter list (content: Html) is filled by the block in braces. Layouts can nest: a section layout wraps main, and a page wraps the section. Extra slots, such as a sidebar or page-specific scripts, are more Html parameters. The same composition idea appears in other stacks, for example in Thymeleaf's fragments and Struts' tiles, and in the action-and-view flow described for Struts.

Reverse routing and assets

@routes.OrderController.cancel(order.getId) generates the URL for a controller action from the routes file. Rename the action or change the path, and the template follows it, or fails to compile if the signature changed. Never write URLs by hand in templates. For static files, @routes.Assets.versioned("path") adds a content hash so browsers cache them safely and pick up changes.

Partials

A fragment of a page is another template with its own parameters, called like a function:

app/views/orders/line.scala.htmlHTML
@(line: models.OrderLine)
<li>@line.getSku() x @line.getQuantity()</li>
HTML
@for(line <- order.getLines()) {
  @orders.line(line)
}

The package path mirrors the directory. Partials make it possible to render a fragment for AJAX responses from the same code that renders the full page, the pattern used with htmx in htmx and Thymeleaf. Forms use helpers: @helper.form(routes.OrderController.create) { @helper.CSRF.formField ... }, and the CSRF field is required on state-changing forms when the CSRF filter is on.

Testing templates

A template is a function, so it can be tested like one. Call render in a unit test and assert on the HTML it returns, with no server running:

java
@Test
void shows_the_cancel_link_only_when_allowed() {
    Content html = views.html.orders.show.render(sampleOrder(), false);

    assertFalse(contentAsString(html).contains("Cancel this order"));
}

contentAsString is available from Play's test helpers and returns the rendered body as a string. Check the parts that carry logic, such as conditional blocks and escaping, and leave pure markup alone, since a test that repeats the HTML is a test that breaks on every design change. For a page-level check, a functional test with WithApplication calls the route and asserts on the status and a fragment of the body, which also exercises the layout and the reverse routes. A template with a compile error never reaches the test, because the build fails first, which is a feature.

Keep templates small. When a template grows past a screen, split the repeated parts into partials, and move any condition that needs a comment into the controller, where it can be named and tested. Developers new to Twirl tend to port too much logic into it because the Scala expressions make it possible, and the habit makes templates the hardest files to change.

Performance notes

Twirl templates compile to classes, so rendering is a method call and string appends, with no parsing at request time. Rendering cost is rarely the bottleneck; a slow page is nearly always a slow query behind it. Stream large pages if they are big enough to matter, and cache a fragment that is expensive to build and the same for every user by caching the controller result, not the template call.

Where this does not apply

Twirl suits server-rendered pages. For an application that serves a JavaScript frontend, Play can return JSON from controllers and skip templates entirely, as in building a REST API with Play. Teams that dislike Scala syntax in templates sometimes pick another engine through a Play module. The template language is documented in the Twirl repository and the Play Java templates guide. For comparison with JSF's component model, see the JSF tutorial.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.