Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if JSP fragment has been set

Tags:

jsp

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.

like image 623
Jared Avatar asked Dec 22 '10 15:12

Jared


1 Answers

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!

like image 144
Jared Avatar answered Oct 10 '22 10:10

Jared