Here, we are going to create a simple and reusable component, which makes it extremely easy to create layout components.

First, we create a "Slot" component. It is used as a placeholder in our layout components.

Slot.java :

   1 package org.myorg.t5demo.components;
   2 
   3 import org.apache.tapestry5.BindingConstants;
   4 import org.apache.tapestry5.Block;
   5 import org.apache.tapestry5.ComponentResources;
   6 import org.apache.tapestry5.annotations.Parameter;
   7 import org.apache.tapestry5.ioc.annotations.Inject;
   8 
   9 public class Slot {
  10 
  11     @Inject
  12     private ComponentResources resources;
  13     @Parameter(name = "id", defaultPrefix = BindingConstants.LITERAL, required = true)
  14     private String id;
  15 
  16     Object beginRender() {
  17         ComponentResources res = resources.getContainerResources();
  18         Block toRender = null;
  19         while (res != null) {
  20             Block temp = res.findBlock(id);
  21             if (temp != null) {
  22                 toRender = temp;
  23             }
  24             res = res.getContainerResources();
  25         }
  26         return toRender;
  27     }
  28 }

Now, we create a layout component,

Layout.tml

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
    <head></head>
    <body>
        <h1>DefaultLayout</h1>
        <t:Slot id="part1"></t:slot>
        <t:Slot id="part2"></t:slot>
    </body>
</html>

Layout.java :

   1 org.myorg.t5demo.components;
   2 
   3 public class Layout {
   4 }

and use it to create a page.

Index.tml

<html t:type="Layout" xmlns:t="http://tapestry.apache.org/schema/tapestry_5_0_0.xsd">
    <t:block id="part2">
        <h1>${part2}</h1>
    </t:block>
</html>

index.java :

   1 package org.myorg.t5demo.pages;
   2 
   3 public class Index {
   4 
   5     public String getPart2() {
   6         return "Part 2";
   7     }
   8 }

Now, try it yourself.

Note that we do not have a single line of java code to handle layouting logic in the layout component. And also note that we do not have to add a block in the page for each slot defined in the layout component.

Sublayout can be easily created, providing defaults for slots defined in upper layouts, or refining the layouts by introducing new slots.

Tapestry5SimpleAndPowerfulLayouts (last edited 2009-09-20 23:20:04 by localhost)