Search code examples
javajspcoding-styledjango-templatescustom-tag

JSP Custom Tags: Is it possible to have a more than start / close tags?


After using the Django template language, I really miss being able to do things like this:

{% if condition %}
    <!-- snip -->
{% else %}
    <!-- snip -->
{% endif %}

When I am using JSP, I am stuck doing something like this:

<logic:equal name="something" value="example">
    <!-- snip -->
</logic:equal>
<logic:notEqual name="something" value="example">
    <!-- snip -->
</logic:notEqual>

or:

<% if (condition) { %>
   <!-- snip -->
<% } else { %>
   <!-- snip -->
<% } %>

Is it possible to write a custom tag that supports else and else if, rather than simply having a pair of tags for each check?

If it's not possible, which is the "preferred" style? Scriptlets or multiple tag pairs? At my organization, most people seem to frown upon scriptlets, but I haven't really heard a good reason why simple conditional statements like the ones I've listed are so bad.


Solution

  • The tags in XML come in pairs, one to open one to close. The three elements of the if then else end do not lend to a nice open and close format. The only other way is to use the choose tag as follows:

    <c:choose>
      <c:when test="${bean.value == 2}">
        <p>True</p>
      </c:when>
      <c:otherwise>
        <p>False</p>
      </c:otherwise>
    </c:choose>
    

    This is the usual way in which to code the if then else structures in jstl.