Question

${something.id!} can help me check the variable exists. But what if I also want to check if it is not 0?

Was it helpful?

Solution

[#if something.id?? && something.id!=0]
   ${something.id}
[/#if]

Or with the standard freemarker syntax:

<#if something.id?? && something.id!=0>
  ${something.id}
</#if>

OTHER TIPS

You could use an if statement such as

<#assign id0=0>
<#assign id1=1>

id0=<#if id0?? && id0 != 0>${id0}</#if>,
id1=<#if id1?? && id1 != 0>${id1}</#if>,
idx=<#if idx?? && idx != 0>${idx}</#if>

Output

id0=, id1=1, idx=

Or better yet use a function. This function uses a default of zero for the value so that it can handle missing/null values. It will return a zero length string if the value is zero or null otherwise the original value.

<#function existsNotZero value=0>
    <#if value == 0>
        <#return "">
    <#else>
        <#return value>
    </#if>
</#function>

<#assign id0=0>
<#assign id1=1>

id0=${existsNotZero(id0)},
id1=${existsNotZero(id1)},
idx=${existsNotZero(idx)}

Output

id0=, id1=1, idx=

Like this:

<#if (something.id!0) != 0>${something.id}</#if>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top