views:

307

answers:

2

I am using struts2 with Velocity 1.5 and Velocity Tools 1.3. In my template I want to do a loop like:

#set ($count = ${item.qty})
#foreach($i in [1..$count])
    ${item.price}
     ...........
#end

${item.qty} is a BigDecimal but it seems like its passed to Velocity as a String maybe. Since this loop does not work. Replacing to $count = 5 works fine, and printing ${item.qty} gives me a result of 5. Velocity 1.5 and Tools 1.3 is the highest version Struts2 will support. Ideas? Workarounds? Thanks

A: 

I think you need to cast/convert it to an integer for your loop to work.

#set ($count = $item.getQty().intValue())
Thilo
I did not realize that was possible with Velocity. Thanks!
Fedor
A: 

perhaps you need to implement your own iterator - it will just store the start and end of the list of bigDecimals, and return the current one. This way, you can have an unlimited sized list of numbers (i assume that is what you wanted because you are using BigDecimals. Otherwise, just use an int or a long):

#set ($countIterator = ${item.qtyIterator})
#foreach($i in $countIterator)
    ${i}
     ....use $i as a string...
#end

and

public class QuantityIterator implement Iterator<BigDecimal> {
   QuantityIterator(BigDecimal start, BigDecimal end) { this.start = start;this.end=end;}
   //..implement the iterator methods like hasNext() etc
   public hasNext() {return this.current.compareTo(this.end) < 0;} //current <= end
   public BigDecimal next() {
      if (!hasNext()) {
         throw new NoSuchElementException();
      }
      this.current = this.current.add(BigDecimal.ONE);
      return this.current;
   }
   public void remove(){throw new UnsupportedException();}
}
Chii
I don't think he really needs a loop that does more iterations than can fit into an integer. That template would take a LONG time to render and produce a HUGE output.
Thilo
@Thilo: that is true - but just in case.....
Chii