You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VLT递归渲染树结构时缩进变量无法回退的问题

问题解决:让Velocity宏中的缩进层级成为循环局部变量

问题原因

Velocity模板的变量作用域是上下文级别的,你代码里出现的持续递增问题,核心是两个细节错误:一是误写了变量名($indentLevels多了个s,引用了全局变量而非宏的参数);二是没正确隔离递归调用的层级值,导致全局变量被持续修改。

修正后的代码

#macro(renderChildItems $item $indentLevel)
  #set($childItems = $transaction.workItems().search().query("linkedWorkItems:parent=$item.fields.id.get AND NOT status:obsolete AND type:(design_decision system_requirement)").sort("id"))
  #foreach($child in $childItems)
    <tr>
      <td style="padding-left:${indentLevel}px">
        $child.render.withTitle.withLinks.openLinksInNewWindow()
      </td>
    </tr>
    #set($nextIndentLevel = $indentLevel + $indentSizeInt)
    #renderChildItems($child $nextIndentLevel)
  #end
#end

关键修正说明

  • 修正变量拼写:把$indentLevels改为$indentLevel,确保使用宏传入的当前层级参数,而非全局变量
  • 隔离层级变量:用新变量$nextIndentLevel存储计算后的缩进值,完全不修改原$indentLevel参数。这样每次递归调用传递的都是当前层级的独立值,递归返回后外层的$indentLevel会保持原值,不会被后续循环影响
  • 变量语法优化:用${indentLevel}包裹变量,避免Velocity把$indentLevelpx解析成一个不存在的变量名

额外注意

  • 提前定义好$indentSizeInt变量(比如#set($indentSizeInt = 20)),代表每一层级增加的缩进像素数
  • 初始调用宏时传入正确的初始值,比如根节点缩进0px:#renderChildItems($rootItem 0)

内容的提问来源于stack exchange,提问作者Sebastiaan Voorderhake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 08:52:43