Freemarker错误预期哈希?

时间:2018-05-17 10:33:05

标签: java date freemarker

我想将即时时间转换为日期,但我收到此错误:

freemarker.template.TemplateException:预期的哈希值。 newDate评估为freemarker.template.SimpleDate

我在Java上这样做:

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

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

我在Freemarker上这样做:

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

谢谢

1 个答案:

答案 0 :(得分:1)

FreeMarker模板通常不会公开Java API,也不允许您按名称访问Java类。我的意思是,在某些情况下确实如此,但一般不像newDate在FreeMarker中没有子变量(如getAsDate)。有些实用程序可以用来公开类的静态方法,例如:

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

其中configuration是您的freemarker.template.Configuration单身人士。实际上,在配置FreeMarker的地方,您可以将DateInstant添加到Configuration.setSharedVariable的单身人士。

然后,您可以将Date.from(Instant.now())写入模板,因为现在有一个DateInstant变量,并且您已经明确告诉FreeMarker公开其静态方法。