Question

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?

Was it helpful?

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.

OTHER TIPS

I ended up doing as you said, Mark:

#macro(condOp $check, $default)
    #if ($check == "")
        $default
    #else
        $check
    #end
#end

And then I can call it like so:

#set ($name = "#condOp($args.get(0), 'default')")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top