LoganBlack
LoganBlack

Reputation: 254

Apache Velocity macro default parameter values

I want to update a macro that's shared between a number of different .vtl files to include a new parameter. However, I only want to change the call in one of my .vtl files and leave the others unchanged. So, I essentially want to add an optional parameter, or a parameter with a default value if no parameter is provided.

The documentation (here) mentions optional default values in the "#macro" section, but after a couple hours of fidgeting with them I can't for the life of me figure out what the proper syntax is.

So I want to take the existing macro:

    #macro( my_macro ) 
        oldValue
    #end

And turn it into a macro like:

    #macro( my_macro $param="oldValue" ) 
        $param
    #end

Where I could call it properly with either of these two calls and get the specified outputs:

    #my_macro()            => oldValue
    #my_macro("newValue")  => newValue

I've tried every permutation of what's specified in the documentation, but can't find anything that works. Does anyone know the proper syntax? Is there possibly a property that I'm missing?

I'm using Velocity 1.7 and VelocityTools 2.0. I'm also using the setting velocimacro.arguments.strict=true if that matters. However, I can't easily change this property without a bunch of updating / retesting.

Upvotes: 6

Views: 3599

Answers (1)

Saljack
Saljack

Reputation: 2352

Default parameter is not work me too. But you can do this workaround:

#macro(my_macro $param)
  #if(!$param)
     #set($param = "oldValue")
  #end
  $param
#end

Upvotes: 1

Related Questions