Hi,
there are three common patterns for inserting separators in a #foreach loop output (a bit simpler than Mikes ;):
## take advantage of a boolean flag #set( $tempNeedSeparator = false )## #foreach( $i in [1..10] )## #if( $tempNeedSeparator ), #end #set( $tempNeedSeparator = true )## $i## #end
## this pattern avoids the inner if #set( $sep = "" ) #foreach( $i in [1..10] )$i$sep#set( $sep = ", " )#end
## The conventional way using velocityCount #foreach( $i in [1..10] )$i#if( $velocityCount > 1), #end#end
Note that the context variable name "velocityCount" might be modified by velocity.properties configuration. So that is the reason I prefer the completely independent form with the $sep variable. A #local($sep)...#end can isolate this from its surroundings...
Hope this helps (maybe this can make its way into a FAQ Wiki?)
Cheers, Christoph
Mike Kienenberger wrote:
Dimitrios Kolovos <[EMAIL PROTECTED]> wrote:
When iterating a collection/array it is usual that you add something after
each iteration except for the last.
#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.
Most of us just use an #if statement and only output the comma on non-first elements. Here's one way to do it off the top of my head -- could be syntax errors. Some of the ##s are probably overkill, but better safe than sorry. Or you could cram it all on one line.
#set( $tempFirstOne = "true" )## #foreach ($i in [1..10])## #if ($tempFirstOne = "true")## #set( $tempFirstOne = "false" )## #else## not $tempFirstOne ,## #end###if ($tempFirstOne = "true") $i## #end##foreach ($i in [1..10])
-Mike
And as long as we're talking about #foreach#else#end, how about
#onFirst? #onLast? #onEmpty?
:-)
Not unreasonable in a templating language, and definitely more readable than the above.
-Mike
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
-- :) Christoph Reck
--------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]
