Built-ins for booleans

c (when used with boolean)

Note:

This built-in exists since FreeMarker 2.3.20.

This built-in converts a boolean to string for a "computer language" as opposed to for human audience. The result will be "true" or "false", regardless of the boolean_format configuration setting, as that setting is meant to specify the format for human consumption. When generating boolean literals for JavaScript and such, this should be used.

If you only generate output that's computer language and isn't read by end-users, you may want to set the boolean_format configuration setting to c (since FreeMarker 2.3.29), in which case ${aBoolean} will have the same output as ${aBoolean?c}.

Note that this built-in also works on strings.

string (when used with a boolean value)

Converts a boolean to a string. You can use it in two ways:

then

Note:

This built-in exists since FreeMarker 2.3.23.

Used like booleanExp?then(whenTrue, whenFalse), fills the same role as the ternary operator in C-like languages (i.e., booleanExp ? whenTrue : whenFalse). If booleanExp evaluates to boolean true then it evaluates and returns its first argument, or else if booleanExp evaluates to boolean false then it evaluates and return its second argument. Off course, all three expression can be arbitrary complex. The argument expressions can have any type, even different types.

An important special property of this built-in is that only one of the argument expressions will be evaluated. This is unlike with normal method calls, where all argument expressions are evaluated, regardless if the method will need them. This also means that the argument that's not needed can even refer to missing variables without causing error. (It still can't be syntactically invalid of course.)

Example:

<#assign foo = true>
${foo?then('Y', 'N')}

<#assign foo = false>
${foo?then('Y', 'N')}

<#assign x = 10>
<#assign y = 20>
<#-- Prints 100 plus the maximum of x and y: -->
${100 + (x > y)?then(x, y)}
Y

N

120
Note:

If you need to choose based on a non-boolean value, you should use the switch built-in instead of nesting multiple then-s into each other, like priority?switch(1, "low", 2, "medium", 3, "high"), or even true?switch(priority <= 1, "low", priority == 2, "medium", priority >= 3, "high").

上一章 首页 下一章