So let's say you have MyUtils
that has a foo()
and a bar()
methods, and you want to access those in the templates.
You can add an arbitrary Java objects to the model using the eval
data loader in data
, like myUtils: eval('new com.example.MyUtils()')
. Then you can issue myUtils.foo()
in the templates. But, you wanted to add the methods at top level. That's also possible. Both in eval
and in a custom DataLoader
(whichever you want to use) you have access to engine
, the fmpp.Engine
object. And then you can pull this trick:
// Note: In case you are using eval, use Java 1.2 syntax (no generics).
TemplateHashModel myUtilsModel = (TemplateHashModel) engine.wrap(new MyUtils());
Map<String, TemplateModel> myUtilsMethodModels = new HashMap<>();
myUtilsMethodModels.put("foo", myUtilsModel.get("foo"));
myUtilsMethodModels.put("bar", myUtilsModel.get("bar"));
return myUtilsMethodModels;
Then you add that Map
to data
without a name. (If you add a Map
to data
without a name, its keys become top-level variables.)
Certainly it can be polished to be nicer, like find methods you want automatically, etc. Plus I did not try this above (so typos are possible). But this is the basic idea. (I guess it would be practical if FMPP had a data loader that loads the static methods of a class... But, right now it doesn't have that.)