usabilitymacrosvelocity

Velocity named parameters for a macro


I have a macro taking several parameters. Some of these are optional and if a parameter is left empty it will replaced with default.

Now the question is how to make this as easy as possible for ordinary web designer. Is there any other possibity apart from my examples to handle this case?

Example 1:

The obvious problem here is the optional values.

#macro (myTag $param1 $param2 $param3)
...
#end

Example 2:

And here the problem is a possible issue when same macro is used more than once and all variables are not set again.

#set ($param1="value1") 
#set ($param2="value2") 
#set ($param3="value3") 

#macro (myTag)
...
#end

Solution

  • As of Velocity 1.6, optional or named parameters are not supported. There was a recent patch submitted with this feature so we might see it available in a future release.

    In the meantime, consider passing in a list or a map of values. For example you can pass in a map of params as follows (requires Velocity 1.5 or greater):

    #macro(myMacro $p)
      item 1: $p.param1
      item 2: $p.param2
    #end
    
    #set($params = {"param1" : "val1", "param2":"val2"})
    #myMacro($params)
    

    displays:

    item 1: val1
    item 2: val2
    

    To handle optional parameters, use an #if within the macro to check for the parameter. Adding new elements to the map is a little messy. Since the Java method "put" returns a value, you have to use #set to dispose of the return value. (Otherwise it's displayed in the resulting text).

    #macro(myMacro $p)
      #if(!$p.param1)#set($dummy = $p.put("param1", "default1"))#end
      #if(!$p.param2)#set($dummy = $p.put("param2", "default2"))#end
      #if(!$p.param3)#set($dummy = $p.put("param3", "default3"))#end
    
      item 1: $p.param1
      item 2: $p.param2
      item 3: $p.param3
    #end
    
    #set($params = {"param1" : "val1", "param2":"val2"})
    #myMacro($params)
    

    displays

    item 1: val1
    item 2: val2
    item 3: default3