Is it possible to call a method that takes parameters from a Freemarker template?
I have an object model that I'm trying to render with Freemarker into a web page. One of the objects has a method to get a sublist of it's contents - taking a parameter that is used to filter the list:
public List getunits(final String type);
I know in JSP you can't do this directly, but you can write custom functions that will allow you to achieve the result you want. How do you solve this in Freemarker? Is it the same with writing custom functions? Or is there some way of actually calling this kind of function?
FreeMarker allows invoking methods that were made available through the model from within expressions.
Assuming your object has been exposed as myBean
you can invoke the method as follows:
<#list myBean.getunits("myType") as unit>
do stuff with ${unit}
</#list>
You don't have to use <list>
, of course, it's just there as an example since your method returns a list.
As ChssPly76 said, you can just peform the method call from within a Freemarker template, as long as you expose the object in the model.
But it's important to keep in mind that if your method returns NULL (for whatever reason), you are going to get a confusing
Expression myBean.getunits() is undefined on line ....
To avoid this, you should better use myBean.getunits(...)!
(notice the exclamation point).
Learn more about how Freemarker handles nulls here: http://freemarker.org/docs/dgui_template_exp.html#dgui_template_exp_missing
来源:https://stackoverflow.com/questions/1362343/how-do-i-call-java-methods-on-an-object-from-a-freemarker-template