Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
Michael Avatar asked Feb 15 '11 14:02

Michael


People also ask

How do you set a Boolean value in Velocity template?

In velocity, there are no explicit data types and hence there is no Boolean variables support. But since velocity has been built on JAVA platform, if you specify a compatible value then it can give you expected results in such operations like the "if" operation (the one shown in your code).

What is macro in velocity?

The #macro directive allows you to name a section of a VTL template and re-insert it multiple times into the template.

Why conditional operator is called ternary operator in Python?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.

What are Velocity templates?

Velocity is a server-side template language used by Confluence to render page content. Velocity allows Java objects to be called alongside standard HTML. If you are are writing a user macro or developing a plugin you may need to modify Velocity content.


1 Answers

You can do

#set($value = "#if($flag)red#{else}blue#end") 
like image 56
aioobe Avatar answered Sep 23 '22 06:09

aioobe