Java Velocity loop add div around every 3 items

戏子无情 提交于 2019-12-12 03:25:47

问题


I'm using the following foreach loop

#foreach( $product in $allProducts )
    <p>$product</p>
#end

to get

<p>something</p>
<p>something</p>
<p>something</p>
<p>something</p>
<p>something</p>
<p>something</p>

Is it possible to wrap a div every 3 items in Velocity? For example to get the following result:

<div>    
<p>something</p>
<p>something</p>
<p>something</p>
</div>
<div>
<p>something</p>
<p>something</p>
<p>something</p>
</div>

I tried using #if ($velocityCount % 3 == 0) in the foreach loop but it doesn't work.


回答1:


You did not tell us which Velocity version you were using. $velocityCount does not exist anymore in last versions (at least in 1.7.x). Try with $foreach.index:

#foreach( $product in $allProducts )
    #if( $foreach.index %3 == 0 )
        #if( !$foreach.first )
        </div>
        #end
    <div>
    #end
    <p>$product</p>
    #if( $foreach.last )
    </div>
    #end
#end



回答2:


It would be a better solution to create the product blocks in java code, before passing them to velocity. I mean something like creating a ProductBlock class which contains a List<Product>, grouping the products into product blocks in java, passing a list of product blocks to the velocity template and consume it like

#foreach( $productBlock in $allProductBlocks )
    <div>
    #foreach( $product in $productBlock.products )
        <p>$product</p>
    #end
    </div>
#end

It will result in less template logic, which is usually a good point.




回答3:


Im not familiar with Velocity, so my syntax might be off, but this can be done using a for loop instead of a forEach:

<div>
for(int i=0;i<products.size;i++){
    <p>$products[i]</p>
    if(i%3==0){
        </div>
        <div>
    }
}
</div>


来源:https://stackoverflow.com/questions/28420066/java-velocity-loop-add-div-around-every-3-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!