Play comes withTwirl, a powerful Scala-based template engine, whose design was inspired by ASP.NET Razor. Specifically it is:
Templates are compiled, so you will see any errors in your browser:
A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.
The template system has been designed to feel comfortable to those used to working with HTML, allowing front-end developers to easily work with the templates.
Templates are compiled as standard Scala functions, following a simple naming convention. If you create aviews/Application/index.scala.html
template file, it will generate aviews.html.Application.index
class that has anapply()
method.
For example, here is a simple template:
@(customer: Customer, orders: List[Order])<h1>Welcome @customer.name!</h1><ul>@for(order <- orders) { <li>@order.title</li>}</ul>
You can then call this from any Scala code as you would normally call a method on a class:
val content = views.html.Application.index(c, o)
The Scala template uses@
as the single special character. Every time this character is encountered, it indicates the beginning of a dynamic statement. You are not required to explicitly close the code block - the end of the dynamic statement will be inferred from your code:
Hello @customer.name! ^^^^^^^^^^^^^ Dynamic code
Because the template engine automatically detects the end of your code block by analysing your code, this syntax only supports simple statements. If you want to insert a multi-token statement, explicitly mark it using brackets:
Hello @(customer.firstName + customer.lastName)! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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. ^
You can also use curly brackets, to write a multi-statement block:
Hello @{val name = customer.firstName + customer.lastName; name}! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dynamic Code
Because@
is a special character, you’ll sometimes need to escape it. Do this by using@@
:
My email is bob@@example.com
A template is like a function, so it needs parameters, which must be declared at the top of the template file:
@(customer: Customer, orders: List[Order])
You can also use default values for parameters:
@(title: String = "Home")
Or even several parameter groups:
@(title: String)(body: Html)
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(myComponent: MyComponent)@(customer: Customer, orders: List[Order])
You can use thefor
keyword, in a pretty standard way:
<ul>@for(p <- products) { <li>@p.name ([email protected])</li>}</ul>
Note: Make sure that
{
is on the same line withfor
to indicate that the expression continues to next line.
If-blocks are nothing special. Simply use Scala’s standardif
statement:
@if(items.isEmpty) { <h1>Nothing to display</h1>} else { <h1>@items.size items!</h1>}
You can create reusable code blocks:
@display(product: Product) = { @product.name ([email protected])}<ul>@for(product <- products) { @display(product)}</ul>
Note that you can also declare reusable pure code blocks:
@title(text: String) = @{ text.split(' ').map(_.capitalize).mkString(" ")}<h1>@title("hello world")</h1>
Note: Declaring code block this way in a template can be sometime useful but keep in mind that a template is not the best place to write complex logic. It is often better to externalize these kind of code in a Scala class (that you can store under the
views/
package as well if you want).
By convention a reusable block defined with a name starting withimplicit will be marked asimplicit
:
@implicitFieldConstructor = @{ MyFieldConstructor() }
You can define scoped values using thedefining
helper:
@defining(user.firstName + " " + user.lastName) { fullName => <div>Hello @fullName</div>}
You can import whatever you want at the beginning of your template (or sub-template):
@(customer: Customer, orders: List[Order])@import utils._...
To make an absolute resolution, useroot prefix in the import statement.
@import _root_.company.product.core._
If you have common imports, which you need in all templates, you can declare inbuild.sbt
TwirlKeys.templateImports += "org.abc.backend._"
You can write server side block comments in templates using@* *@
:
@********************** This is a comment **********************@
You can put a comment on the first line to document your template into the Scala API doc:
@************************************* * Home page. * * * * @param msg The message to display * *************************************@@(msg: String)<h1>@msg</h1>
By default, dynamic content parts are escaped according to the template type’s (e.g. HTML or XML) rules. If you want to output a raw content fragment, wrap it in the template content type.
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:
<p> @Html(article.content)</p>
The template engine can be used as astring interpolator. You basically trade the “@” for a “$”:
import play.twirl.api.StringInterpolationval name = "Martin"val p = html"<p>Hello $name</p>"
Twirl typically renders values of Scala types by callingtoString
method on them. However, if values are wrapped insideOption
or collections (Seq
,Array
,TraversableOnce
), Twirl first unwraps the values and then callstoString
.
For example,
<ul> <li>@Option("value inside option")</li> <li>@List("first", "last")</li> <li>@User("Foo", "Bar")</li> <li>@List("hello", User("Foo", "Bar"), Option("value inside option"), List("first", "last"))</li></ul>
is rendered in the browser as
Found an error in this documentation? The source code for this page can be foundhere. After reading thedocumentation guidelines, please feel free to contribute a pull request. Have questions or advice to share? Go toour community forums to start a conversation with the community.