Tuesday, May 29, 2012

Tapestry - Layouts

To create the same look-n-feel across multiple pages, Tapestry provides the concept of Layout. For example, all pages may have the same header and footer,

A Layout looks very similar to any other Page, except that it is placed in the /components folder instead of /pages.

For now, we will not worry about the difference between a component and a page - they are very similar. Both have a foo.tml file and a corresponding foo.java POJO.

Let us build a Layout for our pages.

In /src/main/resources/org/confucius, create a folder 'components'

In  /src/main/resources/org/confucius/components, create a file Layout.tml, like this:

 <html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">  
   <head>  
     <title>Tapestry</title>  
   </head>  
   <body>  
     <h3>Basic Tutorial Series</h3>  
     
     <t:body/>  
   
     <p>Visit Us @ www.projectconfucius.org</p>  
             
   </body>  
 </html>  


Note that we have included the Tapestry tag library. The magic here is the t:body tag - this will get automatically replaced by the content of the actual page.

Again, this looks just like any other Tapestry page, but because it is in the /components folder, Tapestry treats it like a 'component'.


In /src/main/java/org/confucius, create a folder 'components'

In  /src/main/java/org/confucius/components, create a class Layout.java, like this:

 package org.confucius.components;  
   
 public class Layout {  
   
 }  
   

This is just an empty POJO, but it is necessary to make it available to Tapestry.

Now, update your Index.tml page to use the Layout, like this:

 <html t:type="layout" xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">  
      <body>  
           <h2>${greeting}</h2>  
      </body>  
 </html>  
   


The t:type attribute tells Tapestry to use Layout.tml as the layout component.

If you now rebuild and redeploy HelloWorldTapestry, you will see the header and footer rendered in the page.

Note:
If some of your pages needed a different layout, say Layout2 - then you will need to create a Layout2.tml and Layout2.java, and in your pages, you will say t:type="layout2"

No comments: