Vojtěch
Vojtěch

Reputation: 12426

Freemarker - template preprocessing

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!

Upvotes: 0

Views: 1726

Answers (1)

ddekany
ddekany

Reputation: 31162

This is pretty much why object wrapping exists in FreeMarker; you can present the data to the templates in a custom way. I suppose item belongs to a specific Java class. So you could extend the DefaultObjectWrapper or BeansWrapper to wrap those items specially, and then use Configuration.setObjectWrapper(new YourObjectWrapper()) once where you initialize FreeMarker. (See the source code of DefaultObjectWrapper as an example of customization; it extends BeansWrapper to wrap XML nodes, Jython object, etc., specially.) Thus when you have ${item.name} in the template, it's a call to YourHashModel.get("name") on the Java side (where YourHashModel extends freemarker.template.TemplateHashModel), and in that get method you can have return new SimpleScalar(item.getLocale(currentLocale).get("name")) or like.

Upvotes: 1

Related Questions