tags:

views:

255

answers:

2

Is there a way to do conditional 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?

+2  A: 

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

Mark
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
If the macro only prints a single string you can set it to name. See the edit to my answer.
Mark
Yup. It was those double quotes around the macro call that caught me. Fixed and working now. Thanks (:
peirix
+1  A: 

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
You happened to be adding this just as I was editing my answer with the same example!!
Mark