Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

java - Freemarker Error Expected hash?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...