bofredo
bofredo

Reputation: 2348

Velocity : Breaking out of foreach-loop dynamically

i need to implement a solution in Velocity for breaking out of a foreach-loop at the forelast item of the array. With the API i came to build this, but i doesnt break out and still shows all rows of the loop. Does anyone have a better or working approach for me?

«#if($special)»
  «#foreach($item in $sum)»
    «#if($foreach.hasNext==false)» «#break» «#end»
    «do special stuff» 
  «#end»
«#else»
  «#foreach($item in $sum)»
    «do normal stuff»
  «#end»
«#end»

Upvotes: 0

Views: 1181

Answers (1)

Claude Brisson
Claude Brisson

Reputation: 4160

#if(!$foreach.hasNext) #break #end

or

#if($foreach.hasNext == false) #break #end

should both work for Velocity 1.7+. If you have some doubt about it, you can display

$foreach.hasNext

in the loop and check that it prints true true true ... false.

For prior versions of Velocity, you would have to do it yourself:

#set($count = $num.size())
#foreach($item in $num)
  #if($velocityCount < $count)
    ...
  #end
#end

Note that the $velocityCount variable (which was deprecated in 1.7 and disappeared in 2.0) starts at 1.

Upvotes: 1

Related Questions