Search code examples
javajspjstl

How to access var variable in foreach tag in custom tag?


How to access var value of foreach tag in a custom tag?

<c:foreach items=“{collection}” var=“items”>
    <custom:tag name=items />
</foreach>

How can I assign value of var to attribute name in custom tag?

I used pageContext.getAttribute(\"item"\) but it's not working.


Solution

  • <c:foreach items=“{collection}” var=“items”>
        <c:set var="itemsToPass" value="${items}"/>
        <% pageContext.setAttribute("forEachVar", itemsToPass); %>
        <custom:tag name="${pageScope.forEachVar}"/>
    </c:forEach>
    

    You can use ${pageScope.forEachVar} in your tag (remember to cast it to whatever you need, for example use pageContext.getAttribute(...) to cast the Object to String like String itemsName= (String) pageContext.getAttribute("forEachVar");).