Search code examples
arraysiterationjstlel

JSTL loop through Array to NOT display content


I'd like to use an "Array" in JSTL that looks like this

<c:set var="hideMe" value="${['A','B','C','D']}" scope="application" />

I also have a global VAR called ${checkPageName} which has the name of the current page I am on in it, so I can check against it, as part of the logic (e.g. <c:if test="${checkPageName != hideMe}"> ... </c:if>)

The logic behind this is that if A, B, C or D exist then I will prevent a specific piece of information from being displayed to the user.

Does anyone know how I loop through a JSTL array?

The logic should then decide that if A, B, C or D DO NOT exist, then we display specific information to the user.

I have tried;

<c:forEach items="${hideMe}">
    <c:set var="hide" value="true" />
</c:forEach>

<c:if test="${hide != 'true'}">
    <div class="showMe">
        <h1>Hello Sweetie</h1>
    </div>
</c:if>

Could someone please point me in the right direction?

UPDATE: I have now fixed this myself using <c:forTokens>, see the solution below


Solution

  • So I figured it out in the end;

    <c:set var="hideMe" value="false" />
    
    <c:forTokens items="A,B,C,D" delims="," var="excludeDisplay">
        <c:if test="${checkPageName == excludeDisplay}">
            <c:set var="hideMe" value="true" />
        </c:if>
    </c:forTokens>
    
    <c:if test="${hideMe == 'false}">
        DO SOMETHING
    </c:if>
    

    checkPageName is a global variable I am checking against in my code to validate well, page names...

    So I set a default VAR called hideMe with a value of false, I then use forTokens to create a VAR called excludeDisplay for values A, B, C or D.

    I then check these values against my global variable and if they match overwrite the var hideMe with a value of true, this is then used to trigger the content I want to show. If the VAR is false show the content, if it is true, do nothing.

    I hope this helps someone else, and I am happy to elaborate on some of the murkier points if anyone wants any more information...