Search code examples
apachejsptiles2

Nesting templates in Tiles, why are attributes undefined in the included template?


I use Tiles 2 in my web application, and the basic setup I've got in my tiles.xml file is this:

<tiles-definitions>
    <definition name="mainLayout" template="/jsp/layout.jsp">
        <put-attribute name="header" value=""/>
        <put-attribute name="menu" value="/jsp/defaultMenu.jsp" />
        <put-attribute name="content" value="" />
        <put-attribute name="footer" value="/jsp/footer.jsp" />
    </definition>

    <definition name="HomePage" extends="mainLayout">
        <put-attribute name="content" type="template" value="/jsp/home.jsp"/>
        <put-attribute name="homeClass" value="active" />
    </definition>

    ... rest omitted for brevity.

In layout.jsp, which defines the layout, I include the menu in the appropriate place.

<tiles:insertAttribute name="menu" />

So, then inside my menu template, I wanted to use the homeClass attribute defined in tiles.xml.

<tiles:insertAttribute name='homeClass'/>

but I get an error about the homeClass attribute not being defined. If I do an insertAttribute in my layout.jsp, the value is defined properly, but I need it defined in the menu JSP, included from my layout.

So, my question is: How can I have the homeClass attribute passed correctly not just to my layout template, but to the menu template which is included from the layout template?


Solution

  • I believe you could use nested template definitions:

    <definition name="mainLayout" template="/jsp/layout.jsp">
            <put-attribute name="header" value=""/>
    
            <put-attribute name="menu">
                <definition template="/jsp/defaultMenu.jsp">
                    <put-attribute name="homeClass" value="active"/>
                </definition>
             </put-attribute>
    
            <put-attribute name="content" value="" />
            <put-attribute name="footer" value="/jsp/footer.jsp" />
        </definition>