Search code examples
javajspservlet-filterssitemesh

Is it possible to define a decorator directly in a JSP with Sitemesh?


I know I should define decorators in a configuration file or my own subclass of ConfigurableSiteMeshFilter. For example:

public class SitemeshFilter extends ConfigurableSiteMeshFilter {

    @Override
    protected void applyCustomConfiguration(final SiteMeshFilterBuilder builder) {
        builder.addDecoratorPath("/*", "/WEB-INF/views/layouts/default.jsp");
    }
}

This works for me but this isn't perfect. Can I define what decorator to use directly in a JSP file?

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html sitemesh:decorator="layouts/default.jsp"> <!-- something like this -->
    <head>
        <title>Home</title>
        <meta content="test" name="description" />
    </head>
    <body>
        <h1>Hello world!</h1>
        ${body}
    </body>
</html>

Solution

  • use a meta tag

    We do this all the time.

    In your sitemesh.xml, allow the page to be in a meta tag named decorator like:

       <decorator-mappers>    
          <mapper class="com.opensymphony.module.sitemesh.mapper.PageDecoratorMapper">
             <param name="property.1" value="meta.decorator"/>
             <param name="property.2" value="decorator" />
          </mapper>
      </decorator-mappers>
    

    In your decorators.xml, add a decorator like:

    <decorators>
       <decorator name="default" page="/WEB-INF/decorators/default.jsp" />
       <decorator name="alternative" page="/WEB-INF/decorators/alternative.jsp" />
    <decorators>
    

    Then, in your html or jsp page, you can add a meta tag called decorator to switch between your default and alternative templates:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page session="false" %>
    <html>
        <head>
            <meta name="decorator" content="alternative" />
            <title>Home</title>
            <meta content="test" name="description" />
        </head>
        <body>
            <h1>Hello world!</h1>
            ${body}
        </body>
    </html>
    

    Hope that helps...