【问题标题】:Freemarker function string formatttingFreemarker 函数字符串格式化
【发布时间】:2021-10-26 21:28:34
【问题描述】:

我在 freemarker 的函数中遇到了与字符串格式相关的问题。让我们承认还有下一个功能:

<#function transformWithSign sign amount>
<#--<#local str = amount?string["########.00"]>-->
    <#local str = amount?string>
    <#local str += sign?string>
    <#return str>
</#function>

因此,注释掉的行不起作用,并且出现错误是“freemarker.core.NonMethodException: For "...(...)" callee: Expected a method or function, 但是这已经评估到一个字符串(包装器:ftSimpleScalar): ==> amount?string [in template "html/invoiceTemplate.ftlh" at 52 line, column 23]"

这一行工作正常:

<#local str = amount?string>

那里有什么问题?还是 freemarker 函数不适用于字符串格式化?

【问题讨论】:

    标签: freemarker


    【解决方案1】:

    问题是amount不是一个数字,而是一个看起来像数字的字符串。因此,amount?string 将按原样返回原始字符串,并且该字符串不支持 []() 运算符。如果amount 是一个数字(或日期,或布尔值),那么?string 返回一个支持这些运算符的更花哨的字符串。

    演示问题:

    <#assign amount = 123>
    <#-- Works: -->
    ${amount?string}
    <#-- Also works: -->
    ${amount?string["########.00"]}
    

    但是(注意123左右的引号):

    <#assign amount = "123">
    <#-- Works: -->
    ${amount?string}
    <#-- FAILS: -->
    ${amount?string["########.00"]}
    

    理想情况下,您应该确保amount 以数字形式出现。但是,如果它是字符串,您也可以要求 FreeMarker 进行转换,不过,请确保 amount 中的字符串使用典型的计算机语言数字格式(不是某些本地化格式):

    ${amount?number?string["########.00"]}
    

    【讨论】:

    • 非常感谢@ddekany,已更改为将输入值格式化为amount?number,而amount 传递给func,它按预期工作!
    • @DmitriiVashchenko 那么你应该接受这个答案。
    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多