Apache freemarker 模板分配和比较值
Apache freemarker template assign and compare values
我正在使用下面的赋值语句为变量 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 的值,即使它是“pqr”,但条件总是出现错误。
应该改变什么?
我用过一次
"final_type" : <#if i_type?has_content && i_type?eval == "pqr">1<#else>0</#if>
它运行良好。
为什么原来的例子不起作用是因为你在 <#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")}
我正在使用下面的赋值语句为变量 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 的值,即使它是“pqr”,但条件总是出现错误。
应该改变什么?
我用过一次
"final_type" : <#if i_type?has_content && i_type?eval == "pqr">1<#else>0</#if>
它运行良好。
为什么原来的例子不起作用是因为你在 <#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")}