Velocity template string concatenation

74 views Asked by At

It is my first time to use VTL, and I tried to follow the documentation about string concatenation, but I can’t make it work. Here is the scenario:

I have a payload:

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

The result I got was:

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

Also, how can I get the current date (UTC) in Velocity?

In my Velocity template, I did:

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

The result I want is:

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

There are 1 answers

0
devatherock On

Not sure what the $h object in your velocity context represents, but the JSON output you are expecting can be achieved without it, with a template like the below:

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

Date:

To access the date within the template, you'd need to have a DateTool object in your velocity context. To add it to the context, do something like the below:

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

Once the DateTool object is present in the context, just $date would give you the date/time in the current time zone, in a format like Feb 10, 2024, 7:46:11 PM and $date.getDate().toInstant() would give you the date/time in UTC, in the format 2024-02-11T01:46:11.721Z