tosovvoj
tosovvoj

Reputation: 65

Handling null in Freemarker

Situation:

Problem: New requirements appear: All templates have to be process for preview with no real data. All numbers should be Zero and all string should be ---.

Unsatisfactory solutions:

  1. Remake all templates to check null values. (Lot of work and not safe)
  2. Create Transaction object that contains all default value. (Lot of work)

Well my question is: Can I say to Freemarker, that if he finds null or finds null along the way, that he should use 0 instead if he was expecting number or --- if he was expecting String.

Or do you see any better solution?

Upvotes: 1

Views: 1123

Answers (1)

ddekany
ddekany

Reputation: 31112

If you need to show a dummy data model to the templates, your best bet is probably a custom ObjectWrapper (see Configuration.setObjectWrapper). Everything that reads the data model runs through the TemplateModel-s, and the root TemplateModel is made by the ObjectWrapper, thus it can control what values the templates get for what names. But the question is, when you have to return a dummy value for a name, how can you tell what its type will be? It's not just about finding out if it will be a string or a number, but also if it will be a method (like getNestedObject2) or a hash (something that can be followed by .). What can help there is that FreeMarker allows a value to have multiple types, so you can return a value that can be used as a method and as a hash and as a string, for example. Depending on the application that hack is might be good enough, except, you still have to decide if the value is a string or a number, because ${} will print the numerical value if the value both a string and a number.

Upvotes: 1

Related Questions