How to do an inline if/otherwise (aka ternary operator) in Velocity?
Solution 1
You can do
#set($value = "#if($flag)red#{else}blue#end")
Solution 2
You don't need a #macro or #set directive. The key is using curly brackets for the #else directive.
#if($plural)were#{else}was#end
From the doc (almost at the end of the Conditionals section):
One more useful note. When you wish to include text immediately following a #else directive you will need to use curly brackets immediately surrounding the directive to differentiate it from the following text. (Any directive can be delimited by curly brackets, although this is most useful for #else).
NOTE: Regardless of what the doc says, I since found that it can be necessary to add the curly brackets when using a simple inline if statement.
#if($includePrefix)Affected #{end}Inspection
Solution 3
There is also an approach with reusable macro:
#macro(iif $cond $then $else)#if($cond)$then#else$else#end#end
Then
#define ($value)
#iif("$a > $b", $a, "$b")
#end
Note that velocity docs state that using macros involves some performance impact.
![Michael](https://i.stack.imgur.com/pirkI.jpg?s=256&g=1)
Michael
I'm a software engineer, especially interested in web applications, Java and Python development, Linux-based distros, DevSecOps, automation, containers and CNI. I contribute towards a small number of Open Source projects, balancing out my karma. :D
Updated on July 17, 2022Comments
-
Michael almost 2 years
In pure Java, I could do this:
value = (a > b) ? a : b;
Whereas in Velocity, the long form would be:
#if($a > $b) #set($value = $a) #else #set($value = $b) #end
Is there a short form in Velocity? I want to be able to do an if/otherwise inline.
-
KSev about 10 yearsI tried your solution and it worked. However, it seemed odd that it required a #set directive. So, I searched the documentation for "#{else}" and found the concept clearly documented -- easy to understand but difficult to notice.
-
Alex78191 about 6 yearsYou can delimit directives by spaces.