Use ternary operator in freemarker?
If you're using freemarker 2.3.23 or newer, you can use the then
built-in:
<a href="${a?then('a.htm','b.html')}" target="${openTarget}">
If you're using an older version of freemarker, you can use instead the string
built-in:
<a href="${a?string('a.htm','b.html')}" target="${openTarget}">
When applied to a boolean, the string
built-in will act as a ternary operator.
If you are using older Freemarker versions before 2.3.23, then you can use this macro which provides a straightforward way to do ternary operations:
<#macro if if then else=""><#if if>${then}<#else>${else}</#if></#macro>
It's easy to use, looks nice and quite readable:
<@if someBoolean "yes" "no"/>
Note that it is @if
- and not #if
as in the built-in directive. Here are some more examples.
<!-- `else` is optional -->
<@if someBoolean "someBoolean is true"/>
<!-- expressions -->
<@if (someBoolean||otherBoolean) "hello,"+user.name 1+2+3 />
<!-- with parameter names -->
<@if someBoolean then="yes" else="no" />
<!-- first in list? -->
<#list seq as x>
<@if (x_index==0) "first" "not first"/>
<#list>
For some reason you can't add parenthesis around nameless parameters, if they are non-boolean expressions. That could have increased readability even more.