8

I came across the following tutorial JSP tricks to make templating easier? for using JSP to create page templates (how have I missed this for so long?!?). However, after doing some searching, I cannot seem to figure out how (or if it is possible) to check if a JSP fragment has been set.

Here is an example of what I'm trying to do:

I have a template named default.tag. It has 2 JSP attributes defined as follows:

<%@attribute name="title" fragment="true" required="true" %>
<%@attribute name="heading" fragment="true" %>

Then in the code of the page, I have the <title> element of the page set to <jsp:invoke fragment="title" />. Then later down the page, I have the following:

<c:choose>
    <c:when test="${true}">
        <jsp:invoke fragment="heading" />
    </c:when>
    <c:otherwise>
        <jsp:invoke fragment="title" />
    </c:otherwise>
</c:choose>

Where I have <c:when test="${true}">, I want to be able to check if the heading fragment has been set in order to display it, but if not, then default to the title fragment.

Community
  • 1
  • 1
Jared
  • 4,567
  • 2
  • 26
  • 30

1 Answers1

11

After doing some more messing around, I'm going to answer my own question. It turns out that the name given to the attribute actually becomes a variable as well. Therefore, I can do the following:

<c:choose>
    <c:when test="${not empty heading}">
        <jsp:invoke fragment="heading" />
    </c:when>
    <c:otherwise>
        <jsp:invoke fragment="title" />
    </c:otherwise>
</c:choose>

That was all I needed to do. Seems like I was just trying to make it harder than it needed to be!

Jared
  • 4,567
  • 2
  • 26
  • 30