Search code examples
javahtmljspfor-loopjstl

Avoid multi forEach loop in JSTL in JSP


I want to avoid multi loop in JSTL which is shown by the code presented below. I got attributes WRTSC, DTA, DTA_PRZEDST_TR_OSW from api response and they are passing randomly so that is why the code looks like this.

<c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
<tr>
    <td class="code">${customerAttribute.subGroupName}</td>
    <td class="value">
        <c:forEach items="${customerAttribute.attributes}" var="attribute">
            ${attribute.attrName == 'WRTSC' ? attribute.attrValue : ''}
        </c:forEach>
    </td>
    <td class="value">
        <c:forEach items="${customerAttribute.attributes}" var="attribute">
            ${attribute.attrName == 'DTA' ? attribute.attrValue : ''}
        </c:forEach>
    </td>
    <td class="value">
        <c:forEach items="${customerAttribute.attributes}" var="attribute">
            ${attribute.attrName == 'DTA_PRZEDST_TR_OSW' ? attribute.attrValue : ''}
        </c:forEach>
    </td>
</tr>
</c:forEach>

I need to read every attribute (if there is not attribute sent I need to create empty <td></td> block.

Can it be done in one loop instead of three (in this case this number respresents the number of different attributes).

Thanks for helping.


Solution

  • I've got something like this now. Guys, do you think this is better?

    <c:forEach items="${ctx.model.customerAttributes}" var="customerAttribute">
    <tr>
        <c:set var="WRTSC" value="" />
        <c:set var="DTA" value="" />
        <c:set var="DTA_PRZEDST_TR_OSW" value="" />
    
        <c:forEach items="${customerAttribute.attributes}" var="attribute">
            <c:if test="${WRTSC eq ''}">
                <c:set var="WRTSC" value="${attribute.attrName == 'WRTSC' ? attribute.attrValue : ''}" />
            </c:if>
            <c:if test="${DTA eq ''}">
                <c:set var="DTA" value="${attribute.attrName == 'DTA' ? attribute.attrValue : ''}" />
            </c:if>
            <c:if test="${DTA_PRZEDST_TR_OSW eq ''}">
                <c:set var="DTA_PRZEDST_TR_OSW" value="${attribute.attrName == 'DTA_PRZEDST_TR_OSW' ? attribute.attrValue : ''}" />
            </c:if>
        </c:forEach>
    
        <td class="code">${customerAttribute.subGroupName}</td>
        <td class="value">${WRTSC}</td>
        <td class="value">${DTA}</td>
        <td class="value">${DTA_PRZEDST_TR_OSW}</td>
    </tr>
    </c:forEach>