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

Freemarker模板中遍历输出的数值如何实现累加求和

实现方案

你只需要在遍历列表前声明一个累加变量,每次计算出对应箱数后累加到该变量,遍历结束后输出最终累加值即可,修改后的完整代码如下:

<td>Total Boxes:</td>
<td>
<#if invtransfer?has_content>
    <#if record.custbody_hdr_sort_by == "Item Category">
        <!-- 初始化累加变量,初始值为0 -->
        <#assign totalBoxes = 0 />
        <#list invtransfer?sort_by("x.item.class?split(':')[0]?trim") as x>
            <#assign currCategory>${x.item.class?split(':')[0]?trim}</#assign>
            <#if currCategory == cat>
                <#if x.unit == "PIECE">
                    <#assign boxCount = (x.item.unitstype?split("/")[0]?trim?number) * (x.quantityuom?replace("-", "")?number) />
                <#elseif x.unit == "BOX">
                    <#assign boxCount = x.quantityuom?replace("-", "")?number />
                <#elseif x.unit == "PALLET">
                    <#assign boxCount = (x.item.unitstype?split("/")[1]?trim?number) * (x.quantityuom?replace("-", "")?number) />
                <#else>
                    <#assign boxCount = 0 />
                </#if>
                <!-- 累加到总和 -->
                <#assign totalBoxes = totalBoxes + boxCount />
            </#if>
        </#list>
        <!-- 输出最终总和 -->
        ${totalBoxes}
    </#if>
</#if>
</td>

关键改动说明

  • 遍历invtransfer列表前先初始化累加变量totalBoxes,初始值设为0
  • 原逻辑中直接输出计算结果的部分,改为先将计算值赋值给临时变量boxCount,所有计算结果统一用?number转换为数字类型,避免出现字符串拼接的问题
  • 每计算出一行的箱数就加到totalBoxes中,遍历完成后统一输出总和即可得到累加后的结果

内容的提问来源于stack exchange,提问作者Kenny Punay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:06:00