Apache freemarker模板分配和比较值



我正在使用下面的assign语句为变量i_type赋值。

<#assign i_type>  
<#if x.has("type")>
<#if x.type == "ABC">"ABC"<#else>"${x.type?lower_case}"</#if>
<#else>"pqr"</#if>
</#assign>

然后我想在ftl转换中分配一个变量:

"final_type" : <#if i_type?has_content && i_type == "pqr">1<#else>0</#if>

但是final_type的值在任何情况下都是0。我显式打印了i_type的值,尽管它是" pq& quot;但是condition总是为假。

应该改变什么?

为什么原来的例子不起作用是你有引号在<#else>"pqr"</#if>,并在其他类似的地方。这样,捕获的值本身将包含引号,因为FreeMarker指令的嵌套内容不是表达式,相反,它就像顶级模板内容。所以只写<#else>pqr</#if>

无论如何,更好的写法是:

<#assign i_type =
x.has("type")?then(
(x.type == "ABC")?then(x.type, x.type?lower_case),
"pqr"
)
>

在第二段代码中也不需要i_type?has_content条件,因为总是给i_type赋值。(但即使实际上不是这样,您也可以将i_type!写入默认的缺失值""。)可以这样写:

"final_type" : ${(i_type == "pqr")?then("1", "0")}

有一次我使用

"final_type" : <#if i_type?has_content && i_type?eval == "pqr">1<#else>0</#if>

it work fine.

最新更新