struts 2, tiles 2 dynamic title

Roy Chan picture Roy Chan · Oct 12, 2009 · Viewed 9.2k times · Source

I am using tiles 2.0.6 as my template framework together with struts 2.1.6. I am writing a simple cms page and want to let the user to define the title of each html page.

I have a title definition like this

    <definition name="base" template="/WEB-INF/jsp/templates/base.jsp">
        <put-attribute name="title" value=" "/>
        <put-attribute name="header" value="/WEB-INF/jsp/templates/header.jsp"/>  
        <put-attribute name="content" value="dummy"/>
        <put-attribute name="footer" value="/WEB-INF/jsp/templates/footer.jsp"/>   
        <put-attribute name="search" value="/WEB-INF/jsp/search.jsp"/>
    </definition>    
    <definition name="staticview" extends="base">
        <put-attribute name="title" value=" - Static"/>
        <put-attribute name="content" value="/WEB-INF/jsp/static/view.jsp"/>
    </definition>  

Instead of making the title a jsp, is there a way to dynamically override the title (String) on my header.jsp in the later jsp attribute, for example view.jsp. Or even 1 step further using EL

<put-attribute name="title" value="%{title}"/>

and have it pick up the title on the struts ognl dynamically.

Please advise

Thanks in advance

Answer

Mukus picture Mukus · Feb 28, 2013

In the view page we need to have this -

<title><tiles:getAsString name="title" /></title>

Above will get you the title for the page. Except, since we want the page title to be dynamic, in the tiles.xml configuration, I added

<definition name="page1" extends="base">
    <put-attribute name="title" value="Page 1"/>
    <put-attribute name="content" value="/WEB-INF/jsp/page1.jsp"/>
</definition>
<definition name="page2" extends="base">
    <put-attribute name="title" value="Page 2"/>
    <put-attribute name="content" value="/WEB-INF/jsp/page2.jsp"/>
</definition>

Now this may seem like typing it will make it look like it is static. But every time you view that page, the title should be the same for that page. What better place to have this information that on tiles.xml.

For me it was not the title itself, but I needed different page headings. I didn't want to look at the context attribute to get the path of the page and determine the heading for the page. So, this worked for me and kept everything loosely coupled.

This works if you want a different dynamic heading for each page or anything similar.