Nested Tiles: An Apache Tiles Quick Guide to Nesting Tiles

October 30, 2009

Apache Tiles is a Java Framework used for the templating of Web Applications. Tiles allows developers to define fragments of pages that are combined to create the whole page based on page definitions. The Tiles framework is often used in conjunction with the Apache Struts Model View Controller (MVC) framework. Below are two solutions on how to nest tile elements.

The Problem

During processing Apache Tiles creates a Tiles Context for each level of tile where the attributes defined are only accessible to that context and not any nested tiles. What this means is that you need to pass attributes defined at the top level down to the nested or inner tiles. To illustrate lets assume our web application has 4 main elements:

Header

Menu

Body

Footer

Now lets assume that in for some pages our Body is created by Nesting 2 tiles in it so that instead the page consists of:

Header

Menu

Body Part 1

Body Part 2

Footer

What this would mean is that we would have a layout file that is similiar to:

Solution #1 Defining Nested Tiles in the Tiles Definition

In this solution we define the inner body tile in the definition page and use that definition as the body for the page. So that we end up with a default layout, a page layout, and the body part definitions in our tiles-defs.xml file. A sample is shown below.

Using this method allows you to easily nest tiles and their attributes without having to worry about tiles context and passing attributes to inner nested tiles. The main drawback to this method is that your tiles definitions file can become extremely large depending on your web application.

Solution # 2 Have the Layout file pass attributes to internal tiles

In this approach we update the layout file to pass attributes from its tiles context into the nested tile. So that the nested tile does not need to be defined in the tiles definition but instead the page definitions will specify the attributes that are utilized as shown below.

We now have successfully passed the attributes defined in the tiles definitions into our nested tile by use of the layout file. Although this approach will minimize the size of your tiles definitions file your layout file will need to be expanded to contain all possible attributes that could be utilized by nested tiles, increasing its size.