Friday, December 10, 2010

Dynamically Load Sidebar for Different Page in SiteMesh

It is often the case that your page need to load different sidebar, according to its content. After few tries, I finally figure it out in Sitemesh through "meta" tag.

1. In my project, I prepare two side bars, sidebar.jsp and postsidebar.jsp and place them in the "decorator" directory.




2. In the decorator, default.jsp, get decorator property meta.sidebar and set it to "sidebar" variable. then use jsp:include page to load specific sidebar.

<!-- sidebar -->
  <div id ="sidebar" class="span-7 last">
    
 <c:set var="sidebar" scope="request">
     <decorator:getProperty property="meta.sidebar"/>
 </c:set>
 
  <!-- if no sidebar setted, use default -->
  <c:if test="${empty sidebar}">
   <c:set var="sidebar" scope="request">sidebar</c:set>
  </c:if>
  
  <jsp:include page="${sidebar}.jsp"/>

  </div>

So in your result page, you can specific postsidebar by add the meta tag:
<meta name="sidebar" content="postsidebar" />

and the decorator will be translated into:
<jsp:include page="postsidebar.jsp"/>

0 comments: