开发者

How to do an inline if/otherwise (aka ternary operator) in Velocity?

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.


You can do

#set($value = "#if($flag)red#{else}blue#end")


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜