Search code examples
jspspring-mvcjstljsp-tagsjspx

Custom JSTL tags with body


We are going to use JSTL and custom JSTL-tags for some sort of template-engine in our JSP/spring-project.

Is there a way to create a tag that looks similar like this:

<div id="site">
    <div id="header">Some title</div>
    <div id="navigation"> SOME DYNAMIC CONTENT HERE </div>
    <div id="content"> ${content} </div>
    <div id="footer"></div>
</div>

and use it like this:

<mytags:template>
    <h1>Title</h1>
    <p>My content!</p>
</mytags:template>

i.e. use body-content inside a custom JSTL-tag...

This works:

<mytags:template content="some content... not HTML" />

but is not very useful in our case.


Solution

  • Similar to McDowell's answer, but with more flexibility, is to declare an attribute that is a fragment. http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854

    e.g., //foo.tag tag file

    <%@ attribute name="greeting" fragment="true" %>
    <%@ attribute name="body" fragment="true" %>
    <h1><jsp:invoke fragment="greeting" /></h1>
    <p>body: <em><jsp:invoke fragment="body" /></em></p>
    

    jsp file

    <x:foo>
       <jsp:attribute name="greeting"><b>a fancy</b> hello</jsp:attribute>
       <jsp:attribute name="body"><pre>more fancy body</pre></jsp:attribute>
    </x:foo>
    

    this will produce this markup:

    <h1><b>a fancy</b> hello</h1>
    <p>body: <em><pre>more fancy body</pre></em></p>
    </body>
    

    The main advantage is to be able to have two fragments, instead of just one with a tag.