How to access/get the size of an array/collection in velocity templates?

好久不见. 提交于 2019-12-08 14:26:08

问题


I am using velocity for email templates in my java/spring 3 app.
How could I get the size of an ArrayList added to the model from within the template.


回答1:


I've never used Velocity, but its VTL reference guide says that calling a method is done using $customer.getAddress() or ${purchase.getTotal()}. So I would use ${myArrayList.size()}.




回答2:


A collection can be accessed like any other object, so $collection.size() will contain a value.

Arrays are special cased to behave like List, so though $array.length doesn't work, $array.size() works.

In older versions of Velocity (pre 1.6) you'd use ListTool and ArrayTool.




回答3:


Quote from the developer guide:

Object [] Regular object array, not much needs to be said here. Velocity will internally wrap your array in a class that provides an Iterator interface, but that shouldn't concern you as the programmer, or the template author. Of more interest, is the fact that Velocity will now allow template authors to treat arrays as fixed-length lists (as of Velocity 1.6). This means they may call methods like size(), isEmpty() and get(int) on both arrays and standard java.util.List instances without concerning themselves about the difference.

So using size() works equally well on java.util.List and java arrays.



来源:https://stackoverflow.com/questions/7747254/how-to-access-get-the-size-of-an-array-collection-in-velocity-templates

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