首页 > 解决方案 > VTL 脚本 - ForEach 循环遍历数组

问题描述

#set ($goodSystems = ["one_system","two_system"....])
#foreach ($system in $all.Systems) ##this code must remain the same
#if ($project == "one_system")

如果上下文难以理解,我们深表歉意,因为这在很大程度上已经过清理。我会尽量让它有意义。此代码的#foreach 部分无法更改,因为这是循环访问数据库中所有系统的唯一方法。有些系统我不需要访问因此#if 语句。我一直在使用 if 语句并手动更改 $project 变量,但这会非常耗时。

我正在寻找一种仍然使用#foreach 循环的方法,但在执行其他一些代码(未发布)之前让 $project 变量对 $goodSystems 数组进行检查。这可能吗?提前致谢。

标签: foreachvelocityvtl

解决方案


为什么不简单地做:

#if( $goodSystems.contains($system) )

当然,这是一个快速而懒惰的解决方案,纯粹主义者可能会说,最佳方式是仅在目标元素上循环,必要时拆分循环,如下所示:

#set( $all = { 'Systems': ["one","two","three"] } ) ## testcase init
#set( $good = ["one","two"] )            ## manual input
#set( $junk = $good.retainAll($all) )    ## filter out manual input
#set( $notgood = $all.Systems ) 
#set( $junk = $notgood.removeAll($good)) ## systems with are not good

#foreach( $system in $good )
  ... ## do something for good systems
#end
#foreach( $system in $all.systems )
  ... ## do something for all systems
#end
#foreach( $system in $notgood )
  ... ## do something for systems which aren't good
#end

推荐阅读