TinusSky TinusSky - 6 days ago 6
Java Question

If-else statement inside a parameter of a freemarker macro?

Is it possible to have an if/else statement inside a parameter of a freemarker macro?

I now have:

[#if myForm.id==0]
[#assign action = "add"]
[#else]
[#assign action = "change"]
[/#if]
[@printForm action /]


This is quite a lot of code lines, is it possible to shorten this a bit by putting the if/else construct as a parameter, something like:

[@printForm [if]add[#else]change[/#if] /]

Answer

Update: Starting from FreeMarker 2.3.23, you should use condition?then(whenTrue, whenFalse) for ternary operator. That can have a non-string result and lazy-evaluates its parameters.

In FreeMarker you can approach this as a boolean formatting task: [@printForm (myForm.id == 0)?string('add', 'change') /]

Update: Here's a full working example:

[#ftl]
${.version}

[#macro printForm s]
s: ${s}
[/#macro] 

[#assign myForm = { "id": 0 } ]

[@printForm (myForm.id == 0)?string('add', 'change') /]