【问题标题】:Freemarker Error Expected hash?Freemarker 错误 预期的哈希?
【发布时间】:2018-10-27 14:15:41
【问题描述】:

我想将 Instant 时间转换为 Date,但出现此错误:

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))/]

谢谢

【问题讨论】:

  • 你的意思是Date newDate = Date.from(Instant.now());
  • @YCF_L mm 不,我这样做是为了初始化变量,在 Freemarker 中可以执行 newDate.getAsDate().from(instant.ofEpochSecond(data.time.seconds))
  • 用我的解决方案我想你只需要[#assign dateFormated = newDate/]我不熟悉freemaker
  • @YCF_L 我不能这样做,因为在 Freemarker 上我为每个数据做一个 for 并获取日期,所以我不能将 Java 上的每个日期传递给 freemarker,我可以,但那不是为我工作
  • 嗯,对不起,我不知道

标签: java date freemarker


【解决方案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 的地方使用 Configuration.setSharedVariableDateInstant 添加到该单例中。

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

【讨论】:

  • 我正在这样做:configuration = new Configuration(Configuration.VERSION_2_3_0); 但是当我这样做时 configuration.get... 它不起作用,它不会自动完成。谢谢!
  • 嗯,它应该...如果它编译,你试过了吗?无论如何,如果你创建一个new Configuration 是很可疑的。您已经在某处有一个单例实例。也许你可以自动装配它或其他东西。
猜你喜欢
  • 2020-07-09
  • 1970-01-01
  • 2016-11-16
  • 2014-11-01
  • 1970-01-01
  • 2018-05-19
  • 2011-07-28
  • 2019-07-22
  • 2012-02-24
相关资源
最近更新 更多