LoopTool

Last Updated: Jun 23, 2023
documentation for the dotCMS Content Management System

An Apache convenience velocity tool to use with #foreach loops. It wraps a list with a custom iterator to provide additional controls and feedback for managing loops.

This tool was originally inspired the now-deprecated IteratorTool, which provided similar base functionality but was somewhat more difficult to understand and use. Rather than try to migrate that implementation via deprecation and new methods, it was simplest to just create an entirely new tool that simplified the original API and was easy to augment with useful new features like support for nested (and nameable) loops, skipping ahead in loops, synchronizing multiple iterators, getting the iteration count of loops, identifying if a loop is on its first or last iteration, and so on.

Most functions of this tool became obsolete as of the release of Velocity 1.7, which provides $foreach.hasNext, $foreach.isFirst, $foreach.isLast, $foreach.index and $foreach.count automatically. However, this can still be useful for the more advanced sync and skip features. Also, for very complicated nested loops, the loop naming feature may be easier than doing things like $foreach.parent.parent.

The following example shows how the LoopTool viewtool is mapped in the toolbox.xml file:

    <tool>
        <key>loop</key>
        <scope>request</scope>
        <class>org.apache.velocity.tools.generic.LoopTool</class>
    </tool>

Example

Template:

  #set( $list = [1..7] )
  #set( $others = [3..10] )
  #foreach( $item in $loop.watch($list).sync($others, 'other') )
  $item -> $loop.other
  #if( $item >= 5 )$loop.stop()#end
  #end  

Output:

  1 -> 3
  2 -> 4
  3 -> 5
  4 -> 6
  5 -> 7

Example tools.xml config (if you want to use this with VelocityView):

  <tools>
   <toolbox scope="request">
     <tool class="org.apache.velocity.tools.generic.LoopTool"/>
   </toolbox>
 </tools>

On this page

×

We Dig Feedback

Selected excerpt:

×