 <p>This looks like very close to <a href="http://stackoverflow.com/questions/28420066/java-velocity-loop-add-div-around-every-3-items/28426218#28426218">question 28420066</a>.</p> <p>In Velocity 1.7+, use $foreach.index (0-based), $foreach.count (1-based), $foreach.first and $foreach.last (<a href="http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html#Loops" rel="nofollow">check the doc</a>).</p> <pre><code>&lt;ul&gt; #foreach( $product in $allProducts ) #if( $foreach.index %4 == 0 ) #if( !$foreach.first ) &lt;/ul&gt; #end &lt;ul&gt; #end $product #if( $foreach.last ) &lt;/ul&gt; #end #end &lt;/ul&gt; </code></pre>