Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use ternary operator in freemarker?

I just want to do something like this:

<a href="${ a? 'a.htm' : 'b.htm'}"> 
like image 212
Jack Hu Avatar asked Jul 09 '13 04:07

Jack Hu


People also ask

How do you convert boolean to string in FreeMarker?

string (when used with a boolean value)Converts a boolean to a string. You can use it in two ways: As foo? string("yes", "no") : Formats the boolean value to the first parameter (here: "yes" ) if the boolean is true, and to the second parameter (here: "no" ) if it's false.

How do you add values on FreeMarker?

If you want to insert the value of an expression into a string, you can use ${...} (and the deprecated #{...} ) in string literals. ${...} in string literals behaves similarly as in text sections (so it goes through the same locale sensitive number and date/time formatting).

Is FreeMarker case sensitive?

The string converted to boolean value. The string must be true or false (case sensitive!), or must be in the format specified by the boolean_format setting. If the string is not in the appropriate format, an error will abort template processing when you try to access this built-in.

What is eval in FreeMarker?

eval. This built-in evaluates a string as an FTL expression. For example "1+2"? eval returns the number 3. (To render a template that's stored in a string, use the interpret built-in instead.)


1 Answers

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.


like image 164
obourgain Avatar answered Sep 20 '22 19:09

obourgain