The Variable Component allows you to define Velocity Templates (VTL) to include logic for variable assignment. This feature enhances the flexibility and power of variable manipulation in your Flows.
For details on VTL syntax and usage, see the Velocity User Guide.
Advanced usage scenarios for the Variable Component are shown below, demonstrating how to leverage VTL for common tasks such as concatenating array values and incrementing counters.
To transform an array of values from an API response and pass them to an Assistant or Agent in another variable, you can create a new variable using a VTL script. This script generates plain text content to send to the Assistant.
Suppose you have a variable named {items}, mapped from an API response with the following content:
{
"name": "John",
"age": 23
},
{
"name": "Jane",
"age": 23
}
To create a new variable {userNames} that contains a comma-separated list of names, use the following VTL script:
#foreach( $item in {items} )
$item.name#if( $foreach.hasNext ), #end
#end
This script will assign the following value to {userNames}:
John, Jane
To increment the value of a Number variable, use the following script:
#set( {count} = {count} + 1)
{count}
To cast a String value to an Integer, use this script:
#set( {count} = $number.toNumber({count}) + 1)
{count}
Note: The first line of the script increments the variable by 1, and the second line reassigns the value to the variable. This second line is necessary due to the nature of the variable component editor, which works as a template editor.
The Variable Component also supports working with date and time using built-in date utilities.
To set the current date in a variable using the default format for the current locale:
$date
To apply a custom format (e.g., ISO format):
$date.format("yyyy-MM-dd", $date.getDate())
You can also build date-based phrases to send to an Assistant or Agent. For example, the following script calculates the date 7 days ago and today's date, then formats both:
## Get the calendar
#set( $calendar = $date.getCalendar() )
## Subtract 7 days. The number 5 corresponds to java.util.Calendar.DAY_OF_MONTH
#evaluate( $calendar.add(5, -7) )
#set( $startTime = $date.format("yyyy-MM-dd", $calendar.getTime()) )
#set( $currentTime = $date.format("yyyy-MM-dd", $date.getDate()) )
Show me the news from $startTime till $currentTime
To change the time zone, you need to set the timezone variable with a valid time zone value such as "UTC", "GMT-3", or "GMT+5".
Note: If the timezone variable is not already defined in your Flow, you can create it manually.