---
updatedAt: 2026-11-09T12:31:54.000Z
agentTools:
  projectIndex: https://docs.esputnik.com/llms.txt
---

# Velocity Reference

<HTMLBlock>{`
<p align="right" style="color: gray;">
  <a href="https://docs-ua.esputnik.com/docs/vikoristannya-mozhlivostej-velocity-v-esputnik" style="color: gray; text-decoration: none;"><em>
    Read this article in Ukrainian ⮕
  </em></a>
</p>
`}</HTMLBlock>

Quick reference for Velocity syntax in eSputnik.

For practical examples, see **Velocity in Messages** and **Velocity in Workflows**.

## Variable Formats

| Format                    | Description                                                          |
| ------------------------- | -------------------------------------------------------------------- |
| `$discount`               | If the variable does not exist, outputs the literal text `$discount` |
| `$!discount`              | Silent — outputs nothing if the value is missing                     |
| `${discount}`             | Braces unambiguously delimit the variable name from adjacent text    |
| `$!{discount}`            | Silent and unambiguous — recommended for production use              |
| `${discount\|$otherGift}` | Outputs the fallback value if the variable is missing                |

## Nested Objects

Use dot notation to access fields inside an object:

* `$item.name`
* `$lastProductAdded.externalItemId`
* `$manager.phone`

## Arrays and Indexes

Access an element by index (0-based):

* `$!arrayName[0]`
* `$!items[0].parameterName`

If the specified index does not exist, an error will occur at send time. Use a loop when the array size is not known in advance.

Get the array size:

* `$!arrayName.size()`

Check whether a value is in an array:

* `$!arrayName.contains("value")` — returns `true` if the value is in the array and `false` if it isn't;
* `$!arrayName.indexOf("value")` — returns the index of the value, or `-1` if it isn't there.

For example, to show a block only to contacts whose `cohorts` array contains `premium`:

```
<!--#if($cohorts.contains("premium"))-->
...
<!--#end-->
```

> **Note:** The exact access path depends on the structure of the event payload. Some events contain a plain array; others wrap it inside an object with an `array` field.

## Loops

Iterate over all elements in an array with `#foreach`:

```velocity
#foreach($item in $!arrayName)
  $foreach.count: $!item.name
#end
```

`$foreach.count` is the loop counter, starting from 1.

Stop the loop early with `#break`:

```velocity
#foreach($item in $!arrayName)
  $!item.name
  #if($foreach.count > 5) #break #end
#end
```

In email HTML, wrap directives in comments: `<!--#foreach(...)-->`, `<!--#end-->`

## Assignment

Assign a value to a variable for reuse within the template:

```velocity
#set($var = 'value')
#set($total = $mathTool.add($price, $tax))
```

## Maps

To pick a value by key — for example, a link domain that depends on the cohort — define a map instead of an `#if`/`#elseif` chain and get values from it with `get()`:

```velocity
#set($baseUrl = {
  "dev": "https://dev.example.com/",
  "stage": "https://stage.example.com/",
  "default": "https://example.com/"
})
#if($baseUrl.get($!cohort))
  #set($url = $baseUrl.get($!cohort))
#else
  #set($url = $baseUrl.get('default'))
#end
```

If the key isn't in the map, the `#else` branch sets the default value. To add a new option, add a pair to the map — the condition stays the same.

In email HTML, wrap directives in comments: `<!--#set(...)-->`.

## Conditions

Basic condition:

```velocity
#if($!param == 'value')
  content
#end
```

With alternative:

```velocity
#if($!param == 'value')
  content
#else
  altContent
#end
```

Multiple conditions:

```velocity
#if($!param == 'value1')
  content1
#elseif($!param == 'value2')
  content2
#else
  altContent
#end
```

Check for a non-empty value:

```velocity
#if($!param && $!param != '')
  content
#end
```

## Operators

### Comparison

| Operator | Meaning               |
| -------- | --------------------- |
| `==`     | Equal                 |
| `!=`     | Not equal             |
| `gt`     | Greater than          |
| `lt`     | Less than             |
| `ge`     | Greater than or equal |
| `le`     | Less than or equal    |

### Logical

| Operator       | Meaning     |
| -------------- | ----------- |
| `&&` or `and`  | Logical AND |
| `\|\|` or `or` | Logical OR  |
| `!` or `not`   | Logical NOT |

### String comparison

* `$!firstString.equals($!secondString)`
* `$!firstString.equalsIgnoreCase($!secondString)`

***

## Escaping characters (EscapeTool)

Use `$esc` to output characters that Velocity would otherwise interpret as syntax.

| Expression          | Output               | Use for                                                                    |
| ------------------- | -------------------- | -------------------------------------------------------------------------- |
| `${esc.d}`          | A literal `$`        | Prices next to dynamic values, e.g. `${esc.d}59.99` renders `$59.99`       |
| `$esc.url($!value)` | A URL-encoded string | Values with spaces or special characters passed into a URL query parameter |

Example — encode a value before placing it in a link:

```velocity
#set($program = $esc.url($!data.get('programName')))
```

Then reference `$program` in the URL. See [Dynamic Links in Email](https://docs.esputnik.com/docs/dynamic-links-in-email) for the link-field context.

You can also substitute an event parameter directly into a URL query string, which is useful for passing dynamic tokens or IDs from an event into a link:

```
https://example.com/checkout?token=$esc.url($!data.get('custom_token'))
```

***

## Arithmetic

* `$mathTool.add($v1, $v2)`
* `$mathTool.sub($v1, $v2)`
* `$mathTool.mul($v1, $v2)`
* `$mathTool.div($v1, $v2)`

## Number Formatting

Integer without rounding:

* `$numberTool.integer($v1)`

`$numberTool.integer()` formats the number by locale and adds thousands separators — for example, `1,772,023,737`. For a value that goes into a link or a parameter, such as a timestamp for an external timer, use `$mathTool.toInteger()` instead: it returns a plain integer with no separators.

Money amount with two decimal places:

* `$!numberTool.format('#.00', $v1)`

## Dates

### Output

Current date:

* `$!dateTool.currentDate()`
* `$!dateTool.currentDate('dd.MM.yyyy HH:mm:ss', 'GMT+3')`

Current Unix timestamp:

* `$!dateTool.currentTimeStamp()`

Format a date from the event or contact field:

* `$!dateTool.formatDate('dd.MM.yyyy', $!date)`
* `$!dateTool.formatDate('yyyy-MM-dd HH:mm:ss', $!date)`

`formatDate` also accepts a Unix timestamp in milliseconds — `1495479520000`, for example — and turns it into a readable date. `$!dateTool.currentTimeStamp()` returns the current date in milliseconds as well.

Format in the contact's time zone:

* `$!dateTool.formatInContactTimezone('dd/MM/yyyy HH:mm:ss', $!dateTime)`

The input date has to come in one of these formats: `dd/MM/yyyy HH:mm:ss`, `yyyy-MM-dd'T'HH:mm:ss`, or `yyyy-MM-dd'T'HH:mm:ss'Z'`. The result is rendered in the contact's time zone, and in the organization's time zone when the contact has none.

### Arithmetic

Given `"date": "01/01/2020 12:00"`:

* `$!dateTool.addYears($!date, 2)` → 01/01/2022 12:00
* `$!dateTool.addMonths($!date, 5)` → 01/06/2020 12:00
* `$!dateTool.addDays($!date, 15)` → 16/01/2020 12:00
* `$!dateTool.addHours($!date, 7)` → 01/01/2020 19:00
* `$!dateTool.addMinutes($!date, 15)` → 01/01/2020 12:15

Negative values subtract:

* `$!dateTool.addDays($!date, -7)`

Without a format argument, the date operations read these formats: `dd/MM/yyyy HH:mm`, `dd/MM/yyyy`, `yyyy-MM-dd'T'HH:mm`, and `yyyy-MM-dd`. A date in any other format needs its own format passed as an argument.

To get a date a number of days after the current one, pass the `dd/MM/yyyy HH:mm` format to `currentDate`. `addDays` can't parse the date that `$!dateTool.currentDate()` returns without parameters, and the result is empty:

* `$!dateTool.addDays($!dateTool.currentDate('dd/MM/yyyy HH:mm'), 28)` → 04/12/2026 10:30:00 if the current date is 06/11/2026 10:30

With custom input format — given `"customDate": "12:00 2020-30-04"`:

* `$!dateTool.addYears($!customDate, 2, 'HH:mm yyyy-dd-MM')` → 12:00 2022-30-04

With custom input and output format — given `"dateTime": "2020-05-01T00:00"`:

* `$!dateTool.addDays($!dateTime, 2, "yyyy-MM-dd'T'HH:mm", 'dd-MM-yyyy')` → 03-05-2020
* `$!dateTool.addHours($!dateTime, 7, "yyyy-MM-dd'T'HH:mm", 'dd/MM HH:mm')` → 01/05 07:00
* `$!dateTool.addMinutes($!dateTime, 2, "yyyy-MM-dd'T'HH:mm", 'HH:mm')` → 00:02

### Difference between two dates

Given `"firstDate": "01/01/2019"`, `"secondDate": "05/05/2020"`:

* `$!dateTool.diff($!firstDate, $!secondDate, 'YEARS')` → 1
* `$!dateTool.diff($!firstDate, $!secondDate, 'MONTHS')` → 16
* `$!dateTool.diff($!firstDate, $!secondDate, 'DAYS')` → 490
* `$!dateTool.diff($!firstDate, $!secondDate, 'HOURS')` → 11760
* `$!dateTool.diff($!firstDate, $!secondDate, 'MINUTES')` → 705600

With custom format — given `"customDate1": "17:15 05/05/2020"`, `"customDate2": "10:05 01/01/2019"`:

Both dates have to use the same format. When that format is not one of the defaults, pass it as the fourth argument.

* `$!dateTool.diff($!customDate1, $!customDate2, 'HH:mm dd/MM/yyyy', 'MINUTES')` → 706030

## Strings

Get string length:

* `$!var.length()`

Extract a substring:

* `$!var.substring(startIndex, endIndex)`

Replace part of a string:

* `$!var.replace('oldValue', 'newValue')`

Change case:

```velocity
#set($example = 'Ukraine')
$example.toUpperCase()    → UKRAINE
$example.toLowerCase()    → ukraine
```

Truncate a long value:

```velocity
#set($name0 = $!items[0].name)
#if($name0.length() gt 40)
#set($name0 = $name0.substring(0, 37) + '...')
#end
```

Assign the value to a variable before the condition and output that variable in the message, not the original expression. When one message truncates several values, such as product names in a grid, give each value its own variable name — `$name0`, `$name1`, and so on.

## External Source Data

External source data is available in Velocity when the relevant source is connected and its values are available in the current context.

The syntax is the same Velocity syntax used for other data in eSputnik.

The exact variable path depends on the structure of the data returned by the source and the field names in the source configuration. Use the field names and data structure available in your source settings or test payload.

### Webhook response data

Access webhook response fields by the names exposed in the response, according to its structure. As with other data sources, availability depends on the current context.

***

<br />