2.6. Page Templating

Click supports page templating (a.k.a. Tiles in Struts) enabling you to create a standardized look and feel for your web application and greatly reducing the amount of HTML you need to maintain.

To implement templating define a border template base Page which content Pages should extend. The template base Page class overrides the Page getTemplate() method, returning the path of the border template to render. For example:

package com.mycorp.page;

public class BorderedPage extends Page {

    /**
     * @see Page#getTemplate()
     */
    public String getTemplate() {
        return "/border.htm";
    }
}

The BorderedPage template border.htm:

<html>
  <head>
    <title>$title</title>
    <link rel="stylesheet" type="text/css" href="style.css" title="Style"/>
  </head>
  <body>

    <h2 class="title">$title</h2>

    #parse($path)

  </body>
</html>
    

Other pages insert their content into this template using the Velocity #parse directive, passing it their contents pages path. The $path value is automatically added to the VelocityContext by the ClickServlet.

An example bordered Home page is provided below:

<page path="home.htm" classname="com.mycorp.page.Home"/>

package com.mycorp.page;

public class Home extends BorderedPage {

    public String title = "Home";

}

The Home page's content home.htm:

<b>Welcome</b> to Home page your starting point for the application.

When a request is made for the Home page (home.htm) Velocity will merge the border.htm page and home.htm page together returning:

<html>
  <head>
    <title>Home</title>
    <link rel="stylesheet" type="text/css" href="style.css" title="Style"/>
  </head>
  <body>

    <h2 class="title">Home</h2>

    <b>Welcome</b> to Home page your application starting point.

  </body>
</html>

Which may be rendered as:

Home Page

Figure 2.4. Home Page


Note how the Home page class defines a title model value which is referenced in the border.htm template as $title. Each bordered page can define their own title which is rendered in this template.

Templating with JSP pages is also supported using the same pattern. Please see the Click Examples application for a demonstration.