Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...