The template engine
Play has an efficient templating system which allows to dynamically generate HTML, XML, JSON or any text based format document. The template engine uses Groovy as an expression language. A tag system allows you to create reusable functions.
Templates are stored in the app/views directory.
Template syntax
A template file is a text file, some parts of which have placeholders for dynamically generated content. Dynamic elements of the template are written using the Groovy language. Groovy’s syntax is very close to Java’s.
Dynamic elements are resolved during template execution. The rendered result is then sent as part of the HTTP response.
Expressions : ${…}
The simplest way to make a dynamic element is to declare an expression. The syntax used here is ${…}. The result of evaluating the expressions is inserted in place of the expression.
For example:
<h1>Client ${client.name}</h1>
Tags : #{tagName /}
A tag is a template fragment that can be called with parameters. If the tag has only one parameter, by convention it is called “arg” and its name can be omitted.
For example, this tag inserts a SCRIPT tag to load a Javascript file:
#{script 'jquery.js' /}
A tag has to be closed, either directly or by an end tag:
#{script 'jquery.js' /}
or
#{script 'jquery.js'}#{/script}
For example the list tag allows iteration over any collection. It takes two mandatory parameters:
<h1>Client ${client.name}</h1>
<ul>
#{list items:client.accounts, as:'account' }
<li>${account}</li>
#{/list}
</ul>
Actions : @{…} or @@{…}
You can use the Router to (reverse) generate a URL corresponding to a specified route. From a template you can use the special @{…} syntax to do that.
For example:
<h1>Client ${client.name}</h1>
<p>
<a href="@{Clients.showAccounts(client.id)}">All accounts</a>
</p>
<hr />
<a href="@{Clients.index()}">Back</a>
The @@{…} syntax does the same but generates an absolute URL (notably useful for email, ...).
Messages : &{…}
If your application needs internationalization you can use the &{…} syntax to display an internationalized message:
For example in the files conf/messages we specify:
clientName=The client name is %s
To display this message in a template, simply use:
<h1>&{'clientName', client.name}</h1>
Comment : *{…}*
Comments aren’t evaluated by the template engine. They are just comments...
*{**** Display the user name ****}*
<div class="name">
${user.name}
</div>
Scripts : %{…}%
A script is a more complicated set of expressions. A script can declare some variables and define some statements. Use the {…} syntax to insert a script.
%{
fullName = client.name.toUpperCase()+' '+client.forname;
}%
<h1>Client ${fullName}</h1>
A script can write dynamic content directly using the out object:
%{
fullName = client.name.toUpperCase()+' '+client.forname;
out.print('<h1>'+fullName+'</h1>');
}%
You can use a script to create a structure such as an iteration in your template:
<h1>Client ${client.name}</h1>
<ul>
%{
for(account in client.accounts) {
}%
<li>${account}</li>
%{
}
}%
</ul>
Bear in mind that a template is not a place to do complex things. So, use a tag when you can, or move the computations into the controller or the model object.
Template inheritance
A template can inherit another template, i.e. it can be included as a part of an other template.
To inherit another template, use the extends tag:
#{extends 'main.html' /}
<h1>Some code</h1>
The main.html template is a standard template, but it uses the doLayout tag to include the content:
<h1>Main template</h1>
<div id="content">
#{doLayout /}
</div>
Create tags
You can easily create specifics tags for your application. A tag is a simple template file, stored in the app/views/tags directory. The name of the template file is used as the tag name.
To create a hello tag, just create the app/views/tags/hello.html file.
Hello from tag!
No need to configure anything. You can use the tag directly:
#{hello /}
Retrieve tags parameters
Tag parameters are exposed as template variables. The variable names are constructed with the ‘_’ character prepended to the parameter name.
For example:
Hello ${_name} !
And you can pass the name parameter to the tag:
#{hello name:'Bob' /}
If your tag has only one parameter, you can use the fact than the default parameter name is arg and that its name is implicit.
Example:
Hello ${_arg}!
And you can call it easily using:
#{hello 'Bob' /}
Invoke tag body
If your tag supports a body, you can include it at any point in the tag code, using the doBody tag.
For example:
Hello #{doBody /}!
And you can then pass the name as tag body:
#{hello}
Bob
#{/hello}
Java object extensions in templates
When you use your Java object within the template engine, new methods are added to it. These methods don’t exist in the original Java class and are dynamically added by the template engine.
For example, to allow easy number formatting in a template, a format method is added to java.lang.Number.
It’s then very easy to format a number:
<ul>
#{list items:products, as:'product'}
<li>${product.name}. Price : ${product.price.format('## ###,00')} €</li>
#{/list}
</ul>
Create custom extensions
Your project may have specific formatting needs, in which case you can provide your own extensions.
You only need to create a Java class extending play.templates.JavaExtensions.
For instance, to provide a custom currency formatter for a number:
package ext;
import play.templates.JavaExtensions;
public class CurrencyExtensions extends JavaExtensions {
public static String ccyAmount(Number number, String currencySymbol) {
String format = "'"+currencySymbol + "'#####.##";
return new DecimalFormat(format).format(number);
}
}
Each extension method is a static method and should return a java.lang.String to be written back in the page. The first parameter will hold the enhanced object.
Use your formatter like this:
<em>Price: ${123456.324234.ccyAmount()}</em>
Template extension classes are automatically detected by play at startup. You just have to restart your application to make them available.
Implicit objects available from a template
All objects added to the renderArgs scope are directly injected as template variables.
For instance, to inject a '‘user’' bean into the template from a controller:
renderArgs.put("user", user );
When you render a template from an action, the framework also adds implicit objects:
- session, the Session object
- flash, the Flash scope
- request, the current Request
- params, HTTP params
- play, a reference to play.Play
- lang, the current language
- messages, the messages map
- out, the Writer
Continuing the discussion
The last layer of a play application is the domain object model.