I have a JSP file that generates a list of LIs, where the first and the last item in the list get a special class assigned to them. I currently use the following bit for that:
<c:set var="liclass">
<c:if test="${rowStatus.first}">first</c:if>
<c:if test="${rowStatus.last}"> last</c:if>
</c:set>
<%-- not very pretty --%>
<li<c:if test="${not empty liclass}"> class="${liclass}"</c:if>>
开发者_如何转开发
The problem in this case is that, in the case when there's only one result, the class should become 'first last' (which works), but it becomes first [...] last
, where [...] represents a bunch of whitespace that SO filters away.
It seems that <c:set>
also takes the whitespace caused by the indentation used. I could just solve it by typing it without whitespace:
<c:set var="liclass"><c:if test="${rowStatus.first}">first</c:if><c:if test="${rowStatus.last}"> last</c:if></c:set>
But I'd prefer the readable variant. Another alternative is to pull the result through a function that removes excess whitespace.
Question: Is there an approach or technique to avoid setting whitespace like this in a <c:set>
-tag?
I'd do it straight in value
attribute with help of the conditional operator ?:
.
<c:set var="liclass" value="${rowStatus.first ? 'first' : ''}" />
<c:set var="liclass" value="${liclass}${rowStatus.last ? ' last' : ''}" />
For the not pretty <li>
part, I'd just add
<c:set var="liclass" value="${empty liclass ? 'none' : liclass}" />
and do
<li class="${liclass}">
True, it adds a seemingly worthless class="none"
for non-first/last elements, but who cares?
As to the concrete question, you can trim whitespace left by taglibs by setting the trimDirectiveWhitespaces
attribute of the @page
to true
.
<%@page trimDirectiveWhitespaces="true" %>
(works in Servlet 2.5/JSP 2.1 containers only)
You can also configure it at servletcontainer level. Since it's unclear which one you're using, here's just an Apache Tomcat example: in the JSP servlet entry in Tomcat/conf/web.xml
add/edit the following initialization parameter:
<init-param>
<param-name>trimSpaces</param-name>
<param-value>true</param-value>
</init-param>
Either way, I can't tell from top of head nor guarantee that it would achieve the desired effect of ending up with first last
. You would have to give it a try yourself.
精彩评论