We have a number of Freemarker macros to simplify HTML pages, eg <@macro.textfield id name label .../>
can automatically add a label tag, standard CSS classes, etc. To cover all our use cases, there are a number of parameters with default values.
However, we would ideally like more advanced defaults than simple literals. For example, if a text field doesn't have a custom value
specified, then it should default to getting it from the model using the name
parameter, eg ${parameters[name]!}
. The name, in turn, can usually be derived from the ID; a field with id="foo"
will most likely need name="form.foo"
. Is there an efficient way to do this?
The default value is just a usual expression, thus it can refer to a data model variable (among others) like this: <#macro something name=form.name>
. It can also refer to another macro parameter: <#macro something p1 p2=p1>
. (Order doesn't mater, FreeMarker will figure out the correct evaluation order. Even cyclic dependencies like p1=p2 p2=p1
are allowed, as it can be resolved when you specify at least one of the parameters in the call.)
See also: https://freemarker.apache.org/docs/ref_directive_macro.html#ref.directive.macro