Freemarker Error Expected hash?

2019-09-19 10:34发布

问题:

I want to transform a Instant time to Date but I'm getting this error:

freemarker.template.TemplateException: Expected hash. newDate evaluated instead to freemarker.template.SimpleDate

I'm doing this on Java:

Date newDate = new Date();
Instant instant =  Instant.now();

webContext.put("newDate",new Date());
webContext.put("instant",instant);

And I'm doing this on Freemarker:

[#assign dateFormated = newDate.getAsDate().from(instant.ofEpochSecond(data.time.seconds))/]

Thank you

回答1:

FreeMarker templates don't in general expose Java API-s, or allow you to access Java classes by name. I mean, in some cases it does, but not in general like newDate has no subvariables (like getAsDate) in FreeMarker. There are utilities with which you can expose the static methods of classes, like:

TemplateHashModel staticModels
        = ((BeansWrapper) configuration.getObjectWrapper())
          .getStaticModels();
webContext.put("Date", staticModels.get("java.util.Date"));
webContext.put("Instant", staticModels.get("java.time.Instant"));

where configuration is your freemarker.template.Configuration singleton. Actually, you can add Date and Instant to that singleton with Configuration.setSharedVariable, once where you configure FreeMarker.

And then, you can write Date.from(Instant.now()) into a template, because now there's a Date and and Instant variable, and you have specifically told FreeMarker to expose thier static methods.