Shams Nahid
Shams Nahid

Reputation: 6559

Use JSTL variable in the JSTL loop

I need to access two dependent ArrayList in JSTL in a nested loop. First I iterate a String type ArrayList and then the values from the loop will be used to access another ArrayList.

<c:forEach items="${productCatagoryList}" var="category">
    <c:forEach items=${${category}} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>

Here from the first foreach loop I'll get the category as String value and for all these category, there is another ArrayList containing some products.

So for each of the String value from the first loop will be used for the second foreach loop.

The second line of the code causes an error. How to use the results of the first loop in the second loop ans items?

Upvotes: 1

Views: 530

Answers (1)

Roman C
Roman C

Reputation: 1

You can create a method in the same class with parameter category. It should be a string type. Then you can call this method from EL. Newer EL allows calling methods that you can use instead of a custom function.

<c:forEach items="${productCategoryList}" var="category">
    <c:forEach items=${getProductsForCategory(category)} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>

If you map categories to product like this

Map<String, List<Product>> productCategory;

Then you can simply use a getter for this variable

<c:forEach items="${productCategoryList}" var="category">
    <c:forEach items=${productCategory[category]} var="item">
        ${item.productName}
    </c:forEach>
</c:forEach>

Upvotes: 1

Related Questions