tomcat-taglibs-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Martin Cooper <mart...@apache.org>
Subject Re: Conditional formatting elements of a collection in c:forEach
Date Wed, 11 Feb 2009 17:29:08 GMT
On Wed, Feb 11, 2009 at 8:53 AM, Rashmi <rashmi.sub@gmail.com> wrote:

> Hello everyone,
>
> I'm trying to display a list of items in a collection using JSTL.
>
> Each item in the collection has x, y, z and id variables.
>
> The user can choose whether he wants the display order (of the items
> in the collection) to be
>
> 1) x y z
> 2) z y x
>
> As far as I know the display ordering can be accomplished in two ways:
> 1) as shown in the code snippet below, create two different loops for
> each display format. The drawback with this approach is that a lot of
> the common stuff is duplicated between the two loops.
>
> 2) Have a c:choose , selection within a single loop, which decides
> between the two formats. The drawback is that the the same condition
> checking repeats for each loop iteration.
>
> Is there a way to set the formatting outside the loop , and use that
> format in the loop to address the two drawbacks above.


Assuming you have a resource bundle around somewhere, add two format strings
to the bundle, one for each of your two display orders; use a condition
('when', 'if' or whatever) to set a variable with the appropriate key; then
use that variable to specify the key to <fmt:message> within your loop.

--
Martin Cooper



> <%@ page contentType="text/html;charset=UTF-8" language="java" %>
> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
> <html>
>  <head>
>    <title></title>
>  </head>
>  <body>
>
>        <c:choose>
>            <c:when test="${param.listBy == 'xFirst' }">
>                <c:forEach var="item" items="${requestScope.items}">
>                     ${item.x} ${item.y} ${item.z}
>                     <a href="/show?id=${item.id}">show item</a>
>                     <a href="/edit?id=${item.id}">edit item</a>
>                     <a href="/delete?id=${item.id}">delete item</a>
>                </c:forEach>
>            </c:when>
>            <c:otherwise>
>                <c:forEach var="item" items="${requestScope.items}">
>                     ${item.z} ${item.y} ${item.x}
>                     <a href="/show?id=${item.id}">show item</a>
>                     <a href="/edit?id=${item.id}">edit item</a>
>                     <a href="/delete?id=${item.id}">delete item</a>
>                </c:forEach>
>            </c:otherwise>
>        </c:choose>
>  </body>
> </html>
>
> Any input is appreciated.
>
> -Rashmi
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: taglibs-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: taglibs-user-help@jakarta.apache.org
>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message