How to output <option selected="true"> from JSPX?

krosenvold picture krosenvold · Nov 19, 2009 · Viewed 6.9k times · Source

A few html tags interpret "any" value of a give attribute as "true" -> option tags come to mind.

I frequently end up doing something like this:

<c:choose>
   <c:when test="${isSelected}"/>
        <option selected="true">Opt1</option> 
    </c:when>
   <c:otherwise/>
        <option>Opt1</option> 
   </c:otherwise>
</c:choose>

I know I can declare a custom to encapslate this behaviour but that also gets pretty ugly, unless I code it in java.

Is there a smarter way to do this ?

Answer

Alan Krueger picture Alan Krueger · Dec 10, 2009

One way to approach this would be to use custom tag(s).

I like the approach that the JSP2X converter takes, defining custom tags in your WEB-INF/tags folder that let you do this:

<jspx:element name="option">
    <c:if test="${selected}">
        <jspx:attribute name="selected">selected</jspx:attribute>
    </c:if>
    <jspx:body>Opt1</jspx:body>
</jspx:element>

A more compact approach might be to create a custom tag specifically for an option that did the right thing, taking a boolean value for the selected attribute, emitting a selected="selected" attribute if it's true, not otherwise. This would be a bit more compact:

<jspx:option selected="${selected}">Opt1</option>