velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Shinobu Kawai Yoshida <shinobu.ka...@gmail.com>
Subject Re: Chop output...
Date Fri, 14 Jan 2005 13:26:28 GMT
Hi Dimitrios,

> When iterating a collection/array it is usual that you add something after
> each iteration except for the last.
> 
> e.g.
> 
> #foreach ($i in [1..10])$i,#end
> 
> produces
> 
> 1,2,3..10,
> 
> The only way I know in which I can omit the last comma is to use
> velocityount. Nevertheless, I think it would be more elegant if there was a
> variable (e.g. $output) in the context that represented the so far produced
> text. Then I could call a method like $output.chop(n) and chop the last n
> characters.

Some alternatives:

1. Use a tool.
o.a.c.lang.StringUtils#join(...) does exactly what you want to do. 
Assuming that StringUtils was in the Context as "strings", and $array
contains the array you want to use:
$strings.join($array, ",")
or if it's a list:
$strings.join($list.iterator(), ",")
cf. http://jakarta.apache.org/commons/lang/apidocs/org/apache/commons/lang/StringUtils.html

2. Use the fact that stuff in double quotes are rendered as VTL:
#set($list = "#foreach ($i in [1..10])$i,#end")
$strings.chop($list)
or directly:
$strings.chop("#foreach ($i in [1..10])$i,#end")
cf. http://jakarta.apache.org/velocity/user-guide.html#Velocimacro%20Miscellany

I'm sure there are many other ugly ways, but these are the ones that
pop to my mind right now.

Best regards,
-- Shinobu

--
Shinobu "Kawai" Yoshida <shinobu.kawai@gmail.com>

---------------------------------------------------------------------
To unsubscribe, e-mail: velocity-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: velocity-user-help@jakarta.apache.org


Mime
View raw message