I was wondering, whether there is a way to preprocess freemarker template with some rules – I would like to add some syntactic sugar, which not really a directive, nor method.
Fo instance I have variables, which I print like this:
${item.getLocale(currentLocale).name}
${item.getLocale(currentLocale).text}
${item.parent.getLocale(currentLocale).name}
${item.parent.getLocale(currentLocale).text}
Obviously, the getLocale construct makes the whole expression pretty ugly. What I would like to achieve is to be able to write:
${item.l.name}
${item.l.text}
${item.parent.l.name}
${item.parent.l.text}
So that all the .l. would be during compilation rewritten to .getLocale(currentLocale).
Is there some nice way to do that? Thanks!
This is pretty much why object wrapping exists in FreeMarker; you can present the data to the templates in a custom way. I suppose
itembelongs to a specific Java class. So you could extend theDefaultObjectWrapperorBeansWrapperto wrap those items specially, and then useConfiguration.setObjectWrapper(new YourObjectWrapper())once where you initialize FreeMarker. (See the source code ofDefaultObjectWrapperas an example of customization; it extendsBeansWrapperto wrap XML nodes, Jython object, etc., specially.) Thus when you have${item.name}in the template, it’s a call toYourHashModel.get("name")on the Java side (whereYourHashModelextendsfreemarker.template.TemplateHashModel), and in thatgetmethod you can havereturn new SimpleScalar(item.getLocale(currentLocale).get("name"))or like.