|
Exposing Java Methods to a TemplateThe public TemplateModel exec(java.util.List arguments) throws TemplateModelException; The argument list that FreeMarker supplies is a list of Note: Unlike other languages, such as Perl, FreeMarker does not flatten
complex variables by default. If an object is passed that does not support the
Starting from FreeMarker 2.0, there is also a subinterface of
Like most other models, Note that Methods are first-class objects in FreeMarkerIf you have a hash named ${myBall.getColor()} in the template to invoke the method and retrieve the color of the ball. However, what is less obvious is that you can assign the method to a variable, and use it on its own, like in: <assign getColorOfMyBall = myBall.getColor> ${getColorOfMyBall()} By omitting the parentheses in the assign instruction, you didn't execute the method, rather you assigned the method itself to a variable, and then you have called it separately. This ability is found in several programming languages (Python and Lisp come to mind) and has several applications. Instead of writing <if cond1> ${obj1.method1(arg1, arg2, arg3, arg4, arg5, arg6)} <elseif cond2> ${obj2.method2(arg1, arg2, arg3, arg4, arg5, arg6)} <else> ${obj3.method3(arg1, arg2, arg3, arg4, arg5, arg6)} </if> you can write instead: <if cond1> <assign method = obj1.method1> <elseif cond2> <assign method = obj2.method2> <else> <assign method = obj3.method3> </if> ${method(arg1, arg2, arg3, arg4, arg5, arg6)} Thus sparing yourself from duplicating the argument list three times. Other applications include the ability to pass a method as an argument to another method (we won't explore this into depth now, but it is a very powerful feature). |
|