Avoid spaces in JSTL c: set statement

I have a JSP file that generates an LI list, where the first and last item in the list get a special class assigned to them. I am currently using the following bit:

<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 where there is only one result, the class should become the "first last" (which works), but it becomes first [...] last , where [...] is a bunch a space that SO filters out.

It seems that <c:set> also accepts spaces caused by the indentation used. I could just solve this by typing it without spaces:

 <c:set var="liclass"><c:if test="${rowStatus.first}">first</c:if><c:if test="${rowStatus.last}"> last</c:if></c:set> 

But I would prefer a readable option. Another alternative is to output the result using a function that removes extra spaces.

Question: Is there an approach or method to avoid setting such a space in <c:set> -tag?

+4
source share
1 answer

I would do it directly in the value attribute using the conditional operator ?: .

 <c:set var="liclass" value="${rowStatus.first ? 'first' : ''}" /> <c:set var="liclass" value="${liclass}${rowStatus.last ? ' last' : ''}" /> 

For the not-so-beautiful part <li> I’ll just add

 <c:set var="liclass" value="${empty liclass ? 'none' : liclass}" /> 

and do

 <li class="${liclass}"> 

True, it adds the seemingly useless class="none" for non-first / last elements, but who cares?


As for the specific question, you can trim the spaces to the left of taglibs by setting the trimDirectiveWhitespaces attribute in @page to true .

 <%@page trimDirectiveWhitespaces="true" %> 

(works only in Servlet 2.5 / JSP 2.1 containers)

You can also configure it at the servletcontainer level. Since it is not clear which one you are using, here is an example of Apache Tomcat: 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> 

In any case, I can not say from above, nor can I guarantee that he will achieve the desired effect by reaching the first last . You should try to try yourself.

+7
source

Source: https://habr.com/ru/post/1335982/


All Articles