简体   繁体   English

Apache 速度“通用”宏

[英]Apache Velocity “generic” macro

We are using Velocity to generate a report of the results of a processing recurring task.我们正在使用 Velocity 生成处理重复任务的结果报告。 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, ie 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. Velocity 并不打算用作脚本语言。 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:如果您的 $item class 有一个 get(String attribute) 方法,那么您可以这样做:

#set( $total = $total+$item.get($attribute) )

Otherwise, you will probably need to hack up something with the RenderTool and MathTool from the VelocityTools project.否则,您可能需要使用 VelocityTools 项目中的 RenderTool 和 MathTool 破解一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM