Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a boolean variable to the string "true" or "false"

Tags:

freemarker

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?

like image 869
tangens Avatar asked Oct 02 '09 17:10

tangens


People also ask

Is true a boolean or string?

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).

How do you change a boolean from true to false?

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.

Is string a Boolean variable?

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.

What is the correct value for Boolean variable True or true?

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.


2 Answers

booleanVar?string("true", "false")

Although true/false is default, so

booleanVar?string

should work fine.

like image 169
tsilb Avatar answered Oct 19 '22 20:10

tsilb


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

like image 36
ddekany Avatar answered Oct 19 '22 20:10

ddekany