42

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Michael
  • 7,348
  • 10
  • 49
  • 86

3 Answers3

60

You can do

#set($value = "#if($flag)red#{else}blue#end")
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • I 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. – KSev May 13 '14 at 22:24
26

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
KSev
  • 1,859
  • 1
  • 24
  • 23
8

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.

Vadzim
  • 24,954
  • 11
  • 143
  • 151