Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Velocity statement to add class to last menu item?

Tags:

java

velocity

I have this velocity code for a simple menu:

<div id="header" class="navstrip">

  #foreach( $navItem in $navItems )
     <a href="$navItem.URL">$navItem.Title</a> |
  #end

</div>

I would like to give the last menu link a class of "last". What would the conditional be for that?

like image 610
Conando Avatar asked Dec 22 '22 00:12

Conando


1 Answers

Detecting last item is the most buggy spot in Velocity for some reason, I created 3 bug reports about it and even though it says they are solved - it still doesn't work perfectly to my knowledge.

If you are using Velocity 1.6 and below then there are following options:

1) Using loop tool

#foreach( $navItem in $loop.watch($navItems) )
    #if($loop.last) 
        last 
    #end
#end

But this doesn't work (see bug #1)

2) Using internal counter $velocityCount:

#foreach( $navItem in $navItems)
    #if($velocityCount == $navItems.size()) 
        last 
    #end
#end

This works.

In Velocity 1.7:

1) You should be able to just use $foreach.last:

#foreach( $navItem in $navItems)
    #if($foreach.last) 
        last 
    #end
#end

But this doesn't work again (see bug #2 and bug #3)

2) Comparing current counter to list size:

#foreach( $navItem in $navItems)
    #if($foreach.count == $navItems.size()) 
        last 
    #end
#end

This works.

Yeah, such simple task and so many troubles.

like image 77
serg Avatar answered Jan 09 '23 04:01

serg