tags:

views:

837

answers:

2

Velocity DisplayTool has a useful method:

$display.list($list)

That will format a collection or array into the form "A, B and C".

The problem is lets say I have an ArrayList of objects, how do I output a specific object field instead of the whole object? For example the regular loop would look like this:

#foreach($obj in $list)
   ${obj.title}
#end

For now I just made obj.toString() to return obj.title, but what if I will need another field?

Thanks.

UPDATE Ended up implementing this method myself and committing it to DisplayTools. So it is a part of Tools 2.0 now.

+2  A: 

So you want to end up with a formatted string like "title1, title2 and title3", where each element is the title property of a list of, say, Book objects? Two approaches come to mind:

1) Construct the list of titles yourself manually then hand that off to $display.list(). E.g.,:

#set($titles = [])
#foreach($obj in $list)
  $titles.add($obj.title)
#end
$display.list($titles)

2) Create a Velocity macro to retrieve a given property from a list, call that macro on your book list with the title property, then hand that to $display.list(). E.g.:

#macro(retrieveProperty $list $property $newList)
  #foreach($obj in $list)
    $newList.add(${obj.${property}})
  #end
#end

#set($titles = [])
retrieveProperty($list 'title' $titles)
$display.list($titles)

Hope this helps.

Dov Wasserman
+1  A: 

You might consider extending the DisplayTool to support this. Take a look at the SortTool, it allows you to sort on properties. Copying code from there should give you a good start toward adding this to DisplayTool. And if you do this and feel like sharing, let us know over on the [email protected] list. Heck, if i'm bored some day, i might do this myself.

Nathan Bubna