Skip to content
pramode edited this page Jun 26, 2011 · 10 revisions

Play templates

Simple example

  public class Application extends Controller {

     public static void test() {
       String name = "Arun Kumar";
       render(name);
     } 
   }  

The variable name can be accessed in app/views/Application/test.html as

  ${name}

Objects can be passed to the template. Let's say we have a class Client (defined as a model). Then, in an action in the controller, we can do:

  Client client = new Client();
  client.name = "Arun"
  render(client)

and access the fields of the "client" object from the template:

  ${client.name}

If there is a possibility of "client" being null, we can do:

  ${client?.name}

this will access the field "name" only if "client" is non null.

Using template decorators to share design between multiple pages (#{extends /}, #{doLayout /}, #{get /}, #{set /} )

Template file (test.html):

  #{extends 'layout1.html' /}
  #{set title:'Testing decoration' /}

  This is a page used for testing use of decorations in templates.

Decorations in layout1.html (app/views/layout1.html):

   <html>
   <head>
   <title>#{get 'title' /}</title>
   </head>

   <body>
   <h1>#{get 'title' /}</h1>

   #{doLayout /}

   <hr>
   <em>This is a Play example</em>

   </body>
   </html>

The content of test.html gets inserted into layout1.html by the #{doLayout /} tag.

The "script" tag

The "script" tag is used to insert javascript code:

  #{script 'jquery.js' /}

The result is a line:

  <script type="text/javascript" language="javascript"  src="/public/javascripts/jquery.js"></script>

in the generated HTML. (Note: it seems that "scripts" verifies whether the file exists before generating a line including it).

The "list" tag (for iterating over a collection)

Example template:

   #{extends 'layout1.html' /}
   #{set title:'Testing decoration' /}

   <p>
   <ul>
       #{list items:clients, as:'name'}
       <li>${name}</li>
       #{/list}
   </ul>

The controller task:

    public static void test() {
         List <String> clients = new ArrayList <String> (); 
         clients.add("ram");
         clients.add("pce");
         clients.add("asok");

         render(clients);
    }   

Escaping of special characters like <, > etc.

Read official documentation

Using @ for reverse route generation

Example template:

     The url of this page is: @{Application.test()}
     <p>
     <ul>
           #{list items:clients, as:'name'}
           <li>${name}</li>
           #{/list}
    </ul>

In the routes file, we have mapped the url /test to the function Application.test. So, writing @{Application.test()} will result in the generation of the string /test.

Comments

This is the comment format:

   *{.....}*

Custom template tags

Read docs