开发者

Apache Velocity "generic" macro

开发者 https://www.devze.com 2023-03-16 10:08 出处:网络
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.

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>开发者_如何学Python;
    <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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号