Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional operator in Velocity

Is there a way to do ternary operators in Velocity? This is what I'd like to do:

#set ($name = ($args.get(0) == "") ? "default" : $args.get(0))

Instead of chunky if-else

#if ($args.get(0) == "")
    #set ($name = "default")
#else
    #set ($name = $args.get(0))
#end

Any ideas?

like image 538
peirix Avatar asked Jul 13 '09 13:07

peirix


People also ask

How do you comment in Velocity?

Like the Java programming language, Velocity has single-line and block comments. A single line comment begins with ## and finishes at the end of the line. This is an example of a single line comment in VTL: ## This is a single line comment.

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.

What is Velocity code?

Velocity Codes are attributed to a location. A velocity code associates the location to a SKU's throughput. For example, fast moving items are stored in the lower level locations, or locations reachable by hand, in the bulk zone.

What is Velocity .VM file?

Velocity is a Java-based templating engine. It's an open source web framework designed to be used as a view component in the MVC architecture, and it provides an alternative to some existing technologies such as JSP. Velocity can be used to generate XML files, SQL, PostScript and most other text-based formats.


1 Answers

From experience and reading the VTL Reference there is no way to do this. If you had lots of assignments like this maybe you could look at defining your own velocimacro to try and avoid repeating the if else.

For example, if the macro only prints a single string you could do the following:

#set ($name = "#condOpt($args.get(0), "default")")

The double quotes around the macro call are important as that means the RHS of the #set is parsed.

like image 139
Mark Avatar answered Sep 18 '22 08:09

Mark