In a freemarker template I want to expand a boolean variable to a string like that:
<#assign booleanVar = "test".isEmpty() />
state: ${booleanVar} <#-- this throws an exception! -->
This is what I want to get as output:
state: false
The only way I found to reach this goal by now is:
state: <#if booleanVar>true<#else>false</#if>
Is there a easier way to do it?
We may have a boolean value in string format ('true' or 'false') and we want its boolean equivalent (such as true or false ). Practical application is when we have a check condition value which is stored as a string in database and based on this value we want to perform some operation on our html page (or jsp).
Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.
This distinction is important because strings themselves can be represented as boolean values, but literally any non-empty string has the value True . If this sounds confusing, the important takeaway is to never assign the string literal "False" to a variable that you're intending to use as a False boolean variable.
Boolean variables are displayed as either True or False. Like C, when other numeric data types are converted to Boolean values then a 0 becomes False and any other values become True. When Boolean values are converted to other data types, False becomes 0 while True becomes –1.
booleanVar?string("true", "false")
Although true/false is default, so
booleanVar?string
should work fine.
Starting from FreeMarker 2.3.20, if you want to print true/false (because you are generating JavaScript or such), write ${booleanVar?c}
(?c
for "computer format", also used for numbers). ${booleanVar?string}
is dangerous for that, since somebody can set the boolean_format
setting to yes,no
or something... (BTW, in that case ${booleanVar}
will work too in 2.3.20, and you get yes
and no
.)
See: http://freemarker.org/docs/ref_builtins_boolean.html#ref_builtin_c_boolean
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With