Velocity 模板字符串连接

问题描述 投票:0回答:1

这是我第一次使用VTL,我尝试遵循有关字符串连接的文档,但我无法使其工作。这是场景:

我有一个有效负载:

{
     "name":{
          "firstname": "John",
          "lastname": "Doe"
     }
}

我得到的结果是:

{
     "fullname": "John"-"Doe"
}

另外,如何在 Velocity 中获取当前日期 (UTC)?

在我的 Velocity 模板中,我做了:

#set($firstname=  $root.name.firstname)
#set($lastname=  $root.name.lastname)
#set($fullname=  ${firstname}-${lastname})
{
     $h.outputFormat("json")
     $h.opt("fullname", $fullname, true)
}

我想要的结果是:

{
     "fullname": "John-Doe"
}
velocity velocity-template-language
1个回答
0
投票

不确定速度上下文中的

$h
对象代表什么,但是没有它也可以实现您期望的 JSON 输出,使用如下模板:

#set($firstname= $root.name.firstname)
#set($lastname=$root.name.lastname)
#set($fullname="${firstname}-${lastname}")
{
     "fullname": "$fullname"
}

日期:

要访问模板中的日期,您的速度上下文中需要有一个 DateTool 对象。要将其添加到上下文中,请执行如下操作:

velocityContext.put("date", new DateTool())

一旦 DateTool 对象出现在上下文中,只需

$date
就会为您提供当前时区的日期/时间,格式如
Feb 10, 2024, 7:46:11 PM
$date.getDate().toInstant()
将为您提供 UTC 格式的日期/时间,格式为格式
2024-02-11T01:46:11.721Z

© www.soinside.com 2019 - 2024. All rights reserved.