Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

This follows on from Struts Tags which you should read first, but beware of references to '[0]' and 'that'; what you really want is 'top', as illustrated below. (I finally worked this out from the source code - hopefully this page means you won't have to.)

Referencing the current value

The simple examples print out values from the list using the property tag, which uses the value at the top of the stack by default:

noformat
Code Block
xml
xml
Days:
<ul>
<s:iterator value="days">
    <li><s:property/></li>
    <!-- The following expression is equal: -->
    <li><s:property value="top"/></li>
</s:iterator>
</ul>

But if you're doing anything other than print the value, you probably need to refer to it specifically. Do this:

noformat
Code Block
xml
xml
Most days:
<ul>
<s:iterator value="days">
    <s:if test="top != 'Monday'">
        <li><s:property/>
    </s:if>
</s:iterator>
</ul>

Iterating over a list of objects

noformat
Code Block
xml
xml
<s:iterator value="employees">
    <s:property value="name"/> is the <s:property value="jobTitle"/><br>
</s:iterator>

...

Iterating over a list of lists

noformat
Code Block
xml
xml
<table>
    <s:iterator value="grid">
        <tr>
        <s:iterator value="top">
            <td><s:property/></td>
        </s:iterator>
        </tr>
    </s:iterator>
</table>

...

In this example, 'countries' is a list of country objects, each of which has a name and a list of cities. Each city has a name.

noformat
Code Block
xml
xml
<s:iterator value="countries">
    <s:iterator value="cities">
        <s:property value="name"/>, <s:property value="[1].name"/><br>
    </s:iterator>
</s:iterator>

...

Both the country and city objects have a 'name' property. As you'd expect, the reference to 'name' on its own gives you the city name. To access the country name - effectively "hidden" by the city name - we refer to a specific position on the stack: '[1]'. The top of the stack, position 0, contains the current city, pushed on by the inner iterator; position 1 contains the current country, pushed there by the outer iterator.

Actually, as Patrick points out in his comment on Iteration Tags, the '[n]' notation refers to a sub-stack beginning at position n, not just the object at position n. Thus '[0]' is the whole stack and '[1]' is everything except the top object. In our example, we could have been more specific about getting the country name and said '[1].top.name'.

Misc

If no value is specified, iterator will try to grap object from the 'top' of the stack. If it is not iterable, ClassCastException will be thrown in the process. @see com.opensymphony.webwork.views.jsp.IteratorTag#doStartTag