Q:

Apache Velocity "generic" macro

We are using Velocity to generate a report of the results of a processing recurring task.
We pass in a list of the processed packages and the associated results.
#foreach($pkg in $packages)
  <tr>
    <td>$pkg.name</td>
    <td>$pkg.numItems</td>
    <td>$pkg.processingTime</td>
    <td>$pkg.numErrors</td>
  </tr>
#end

Now we want to include a summary, i.e. we want to sum up the different results. We though about using a "generic" macros to which we can pass the list and the name of the attribute which should be summed up. Something like:
#macro(sum $list $attribute)
#set($total=0)
#foreach($item in $list)
#set($total =$total+$item.$attribute)
#end
$total
#end

But this do not work - Is it somehow possible to write a "generic" macro to calculate the sum of any attribute of the items of a list or do we have to either calculate them totals before calling velocity or calculate them for each attribute individually?

A:

Velocity isn't meant to be used as a scripting language.  So
#set( $total = $total+$item.$attribute )

will not work as you hope.  If your $item class had a get(String attribute) method, then you could do:
#set( $total = $total+$item.get($attribute) )

Otherwise, you will probably need to hack up something with the RenderTool and MathTool from the VelocityTools project.

