2009-10-20 91 views
4

我们将在我们的JSP/spring-project中为某种模板引擎使用JSTL和自定义JSTL标签。自定义JSTL标签与主体

有没有一种方法来创建一个标签,看起来像这样类似:

<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> 

,并使用它像这样:

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

即使用自定义JSTL标签体内的内容。 ..

这工作:

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

但在我们的案例中并不是非常有用。

回答

5

与McDowell的答案类似,但具有更大的灵活性,是声明一个属性是一个片段。 http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854

例如, //foo.tag标记文件

<%@ 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文件

<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> 

这会产生这种标记:

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

主要优点是可能够有两个片段,而不是只有一个标签。

+0

不好的一面是它更冗长。 – 2010-02-23 05:15:15