13

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?

moribvndvs
  • 42,191
  • 11
  • 135
  • 149
peirix
  • 36,512
  • 23
  • 96
  • 126

3 Answers3

7

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.

Martin Serrano
  • 3,727
  • 1
  • 35
  • 48
Mark
  • 28,783
  • 8
  • 63
  • 92
  • Is there a way to get a macro to act like a function? So that it will return a variable? So that I could do `#set ($name = condOpt($args.get(0), "default"))` If I made the macro do a check on `$args.get(0)` to see if it was empty or not.. – peirix Jul 13 '09 at 13:26
  • If the macro only prints a single string you can set it to name. See the edit to my answer. – Mark Jul 13 '09 at 13:42
  • Yup. It was those double quotes around the macro call that caught me. Fixed and working now. Thanks (: – peirix Jul 13 '09 at 13:45
4

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')")
peirix
  • 36,512
  • 23
  • 96
  • 126
  • You happened to be adding this just as I was editing my answer with the same example!! – Mark Jul 13 '09 at 13:46
0

For the record, with Velocity 2.1+, you can provide alternate reference values:

${args[0]|'default'}
Claude Brisson
  • 4,085
  • 1
  • 22
  • 30