Freemarker Error Expected hash?

廉价感情. 提交于 2019-12-13 08:39:14

问题


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.



来源:https://stackoverflow.com/questions/50389281/freemarker-error-expected-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!