Search code examples
velocityternary-operator

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?


Solution

  • 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.