发布于 2016-05-16 15:31:07 | 837 次阅读 | 评论: 0 | 来源: PHPERZ

Velocity模板支持各种集合类型的迭代。

  • Object[] Velocity包装数据对象到迭代对象中,可以将其当做固定长度的List,可以调用size()、isEmpty()和get(int)。

  • java.util.Collection Velocity将使用iterator()方法获取一个Iterator用于循环,因此,如果你实现了Collection接口,请确

    保iterator()返回一个Iterator。

  • java.util.Map Velocity依赖接口的values()方法获取一个Collection接口,调用iterator()方法检索Iterator用于循环。

  • java.util.Iterator、java.util.Enumeration 只是暂时支持。

  • 任意不返回null的public Iterator iterator()方法。

1    Map

迭代Map中的Key,通过Key获取Map中的元素,来带到迭代的功能。

<ul>

#foreach( $key in $allProducts.keySet() )

    <li>Key: $key -> Value: $allProducts.get($key)</li>

#end

</ul>

2    集合

Velocity可以通过简单的方式获取循环中的计数器。

<table>

#foreach( $customer in $customerList )

    <tr><td>$foreach.count</td><td>$customer.Name</td></tr>

#end

</table>

Velocity也可以通过简单的方式告诉你,是否是最后一次循环。

#foreach( $customer in $customerList )

    $customer.Name#if( $foreach.hasNext ),#end

#end

如果你想要#foreach循环一个基于0的索引,你能使用$foreach.index替代$foreach.count。同样,提供$foreach.first

和$foreach.last。如果你想要访问外部循环的#foreach循环的属性,你能直接通过$foreach.parent或$foreach.topmost属性

引用它们(例如,$foreach.parent.index或$foreach.topmost.hasNext)。

可以设置循环允许执行的最大次数。默认没有最大值(表示为0或更小),但这能在velocity.properties文件中设置为任意数

值。

directive.foreach.maxloops = -1

如果你想要终止foreach,你现在能使用#break指令终止循环。

## list first 5 customers only

#foreach( $customer in $customerList )

    #if( $foreach.count > 5 )

        #break

    #end

    $customer.Name

#end

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务