Setting page title dynamically with tiles2 and spring mvc

suicide picture suicide · Mar 28, 2011 · Viewed 9.3k times · Source

I've been asking myself this question for quite some time and I haven't found a nice solution for this on the web.

So I am using Tiles2 and Spring MVC and I'd like to set the page title dynamically within the body tile. Is there a way?

<definition name="mainTemplate" template="/WEB-INF/template/main.jsp">
 <put-attribute name="header" value="/WEB-INF/template/header.jsp" />
 <put-attribute name="footer" value="/WEB-INF/template/footer.jsp" />
 <put-attribute name="body" value="/WEB-INF/template/blank.jsp" />
</definition>

<definition name="list" extends="mainTemplate">
 <put-attribute name="body" value="/WEB-INF/jsp/list.jsp" />
</definition>

my current solution is setting the title within the controller

 model.addAttribute("pageTitle", "blubb");

and the doing a c:out in the template

Answer

DwB picture DwB · Mar 28, 2011

Tiles Technique

If by "I want to set the page title dynamically" you mean "I want to set the page title based on the tile that is being displayed and I want to use a tiles feature to do it" then:

  1. Define a title property; something like this: <put-attribute name="pageTitle" value="Title"/>
  2. Reference the pageTitle property in the layout for the page; something like this: <title><tiles:getAsString property="pageTitle"/></title>
  3. Set the pageTitle property in any tile that matters; <definition blah blah blah><put-attribute name="pageTitle" value="blah blah blah"/></definition>

Variable Technique

The simplest way to do this technique is to add an attribute to the model and to reference said attribute with an el expression. For example,

You might do this in your controller:

String pageTitle;

pageTitle = "something";
Model.add("PageTitle", pageTitle);

Then reference the "PageTitle" attribute in your page like this:

<head>
<title>${PageTitle}</title>

You can use c:out like this:

<head>
<title><c:out value="${PageTitle}"/></title>