I need to hide an element if certain values are present in the JSP
The values are stored in a List so I tried:
If you are using EL 3.0+, the best approach in this case is as this other answer explained in another topic:
For a
Collection
it's easy, just use theColleciton#contains()
method in EL.<h:panelGroup id="p1" rendered="#{bean.panels.contains('p1')}">...</h:panelGroup> <h:panelGroup id="p2" rendered="#{bean.panels.contains('p2')}">...</h:panelGroup> <h:panelGroup id="p3" rendered="#{bean.panels.contains('p3')}">...</h:panelGroup>
For an
Object[]
(array), you'd need a minimum of EL 3.0 and utilize its new Lambda support.<h:panelGroup id="p1" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p1').get()}">...</h:panelGroup> <h:panelGroup id="p2" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p2').get()}">...</h:panelGroup> <h:panelGroup id="p3" rendered="#{bean.panels.stream().anyMatch(v -> v == 'p3').get()}">...</h:panelGroup>
If you're not on EL 3.0 yet, you'd need to create a custom EL function. [...]
You need to use the fn:contains() or fn:containsIgnoreCase() function.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
...
<c:if test="${not fn:containsIgnoreCase(mylist, 'apple')}">
<p>Doesn't contain 'apple'</p>
</c:if>
or
<c:if test="${not fn:contains(mylist, 'Apple')}">
<p>Contains 'Apple'</p>
</c:if>
Note:
This will work like mylist.toString().contains("apple")
and if this is not what you are looking for better use a other approach.
I found this solution amazing.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.
The following is more of a workaround than an answer to your question but it may be what you are looking for.
If you can put your values in a map instead of a list, that would solve your problem. Just map your values to a non null value and do this <c:if test="${mymap.myValue ne null}">style='display:none;'</c:if>
or you can even map to style='display:none;
and simply output ${mymap.myValue}