30

In velocity, I want to do something different in the last loop.

What is the correct idiom?

RELATED: Last iteration of enhanced for loop in java

Community
  • 1
  • 1
flybywire
  • 261,858
  • 191
  • 397
  • 503
  • @ratchet: same as related question: I am concatenating things with a separator in between and don't want to put the separator after the last item – flybywire Nov 19 '11 at 20:01

4 Answers4

73

You can use a test if you are in last iteration::

#foreach( $item in $list )
    $item.text #if( $foreach.hasNext ), #end
#end
soulcheck
  • 36,297
  • 6
  • 91
  • 90
19

@soulcheck's answer is what you need, but be aware that the $foreach variable is only available in velocity 1.7, if you're using an earlier version you can use:

#foreach( $item in $list )
    $item.text #if( $velocityHasNext ), #end
#end

However, the $velocityHasNext variable is deprecated in versions 1.7 and removed in 2.0 in favour of $foreach.hasNext.

Mark Rhodes
  • 10,049
  • 4
  • 48
  • 51
8

The idiom I use is to save the optional text to be added if the loop doesn't finish.

#set($sep = "")    
#foreach($item in $list)
 $sep$item
 #set($sep = ", ")
#end
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • How would I solve this https://stackoverflow.com/questions/62713626/velocity-template-loop-through-array-to-create-string ? – hyprstack Jul 03 '20 at 11:27
2

This worked for me in an older version of Velocity

#if($velocityCount < $list.size()), #end
Jon Lewis
  • 21
  • 2