6

Is it possible to access JSTL's forEach variable via code from within the loop?

<c:forEach items="${elements}" var="element">
    <% element.someMethod(); %>
</c:forEach>

2 Answers 2

3

Well, I believe "element" is stored in the page context.

<c:forEach items="${elements}" var="element">
    <% ((Element) pageContext.getAttribute("elements")).someMethod(); %>
</c:forEach>
Sign up to request clarification or add additional context in comments.

3 Comments

Just out of idle curiosity, where'd you find this method of access?
I've put things in session and request contexts many times for use in a JSP. Plus I knew that the page context is like them.
minor fix: pageContext.getAttribute("element") instead of pageContext.getAttribute("elements")
-1

Edit following the correction of the example:

Yes, it is possible to access the var inside the c:forEach

Here's an example:

<c:forEach items="${elements}" var="element">
    ${((Element)element).someMethod()}
</c:forEach>

See c:forEach in the JSTL Documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.