8.11. Using Velocity Tools in Templates¶
8.11.1. Overview¶
Velocity Tools are powerful utilities that extend Apache Velocity templates with specialized functionality for common operations like date formatting, mathematical calculations, and number formatting. These tools are automatically available in your templates and provide a rich set of methods to manipulate and format data dynamically.
The tools are accessed using the dollar sign ($) followed by the tool name and method. For example, $math.add(5, 3) uses the MathTool to perform addition.
8.11.2. Available Tools¶
NSG provides several built-in tools:
- Date Tool ($date and $dateTime) - Format dates and times, work with time zones, and get timestamps
- Math Tool ($math) - Perform mathematical operations
- Number Tool ($number) - Format and display numbers with custom patterns
8.11.3. Date Tool¶
The Date Tool provides comprehensive date and time formatting capabilities, including timezone support and timestamp conversion.
8.11.3.1. Basic Date Formatting¶
Format dates using custom patterns:
Date: $date.format('EEEE d MMMM HH:mm z', $testDate, $dateTime.defaultLocale, $dateTime.get('America/Los_Angeles'))
Output: `Thursday 30 September 17:00 PDT`
- $date.format() is a tool call that takes following arguments:
- date/time format
- timestamp value. This can be a constant or the value of object attribute, for example you can call $date.format(‘format’, $alert.activeSince)
- locale (optional)
- timezone (optional)
Tool $date.format() returns date and time passed as second argument, formatted according to the first argument. If locale and timezone are provided, the date/time will be formatted according to the locale and converted to the requested time zone, taking into account possible daylight shift.
last two arguments are optional. If you want to pass timezone info, you must also pass locale. Get standard timezone objects by calling dateTime tool as shown in the example, it accepts standard timezone names such as America/Los_Angeles or UTC. Note that this takes care of the daylight savings shift automatically.
8.11.3.2. Supported formats¶
Here is a non-exhaustive list of date/time formats supported by the Date Tool
Combined date and time formats:
$dateTool.format('default', $testDate)
$dateTool.format('full', $testDate)
$dateTool.format('long', $testDate)
$dateTool.format('medium', $testDate)
$dateTool.format('short', $testDate)
Gives this in the output:
03-Jan-2012 00:00:00
Tuesday, 3 January 2012 00:00:00 o'clock GMT
03 January 2012 00:00:00 GMT
03-Jan-2012 00:00:00
03/01/12 00:00
To get just the date without time, add sufix ‘_date’:
$dateTool.format('default_date', $testDate)
$dateTool.format('full_date', $testDate)
$dateTool.format('long_date', $testDate)
$dateTool.format('medium_date', $testDate)
$dateTool.format('short_date', $testDate)
Gives this in the output:
03-Jan-2012
Tuesday, 3 January 2012
03 January 2012
03-Jan-2012
03/01/12
To get just the time, add suffix ‘_time’
$dateTool.format('default_time', $testDate)
$dateTool.format('full_time', $testDate)
$dateTool.format('long_time', $testDate)
$dateTool.format('medium_time', $testDate)
$dateTool.format('short_time', $testDate)
Gives this in the output:
00:00:00
00:00:00 o'clock GMT
00:00:00 GMT
00:00:00
00:00
Custom formatting is also supported: “YYYY/MM/DD HH:mm:ss”
For more details on date/time format patterns, see the SimpleDateFormat documentation.
Letter | Date or Time Component | Presentation | Examples |
---|---|---|---|
G | Era designator | Text | AD |
y | Year | Year | 1996; 96 |
Y | Week year | Year | 2009; 09 |
M | Month in year (context sensitive) | Month | July; Jul; 07 |
L | Month in year (standalone form) | Month | July; Jul; 07 |
w | Week in year | Number | 27 |
W | Week in month | Number | 2 |
D | Day in year | Number | 189 |
d | Day in month | Number | 10 |
F | Day of week in month | Number | 2 |
E | Day name in week | Text | Tuesday; Tue |
u | Day number of week (1 = Monday, …, 7 = Sunday) | Number | 1 |
a | Am/pm marker | Text | PM |
H | Hour in day (0-23) | Number | 0 |
k | Hour in day (1-24) | Number | 24 |
K | Hour in am/pm (0-11) | Number | 0 |
h | Hour in am/pm (1-12) | Number | 12 |
m | Minute in hour | Number | 30 |
s | Second in minute | Number | 55 |
S | Millisecond | Number | 978 |
z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 |
Z | Time zone | RFC 822 time zone | -0800 |
X | Time zone | ISO 8601 time zone | -08; -0800; -08:00 |
8.11.3.3. Working with Time Zones¶
Format dates in different time zones:
## UTC timezone
Date: $date.format('EEEE d MMMM HH:mm z', $testDate, $dateTime.defaultLocale, $dateTime.utc())
## Specific timezone
Date: $date.format('EEEE d MMMM HH:mm z', $testDate, $dateTime.defaultLocale, $dateTime.get('America/Los_Angeles'))
8.11.3.4. Unix Timestamps¶
Tool $dateTime.timestamp() returns current time as unix timestamp (in seconds). Tool $dateTime.timestampMs() returns timestamp in milliseconds:
## Unix timestamp in seconds
Current time: $dateTime.timestamp()
## Unix timestamp in milliseconds
Current time (ms): $dateTime.timestampMs()
you can apply $date.format() to the current time if you need to format it:
Current time: $date.format('EEEE d MMMM HH:mm z', $dateTime.timestamp())
Current time: $date.format('EEEE d MMMM HH:mm z', $dateTime.timestamp(), $dateTime.defaultLocale, $dateTime.get('America/Los_Angeles'))
8.11.4. Math Tool¶
The Math Tool enables mathematical calculations directly within your templates [[4]](https://velocity.apache.org/tools/1.4/generic/MathTool.html).
8.11.4.1. Basic Operations¶
Perform arithmetic operations on variables:
Sum: $math.add($a, $b)
Product: $math.mul($a, $b)
If $a = 10 and $b = 5, this produces: Output: `Sum: 15, Product: 50`
8.11.4.2. Advanced Calculations¶
Combine multiple operations for complex calculations:
## Calculate tax and total
Tax (10%): $math.mul($amount, 0.1)
Total: $math.add($amount, $math.mul($amount, 0.1))
8.11.5. Number Tool¶
The Number Tool provides flexible number formatting capabilities [[1]](https://velocity.apache.org/tools/devel/apidocs/org/apache/velocity/tools/generic/NumberTool.html).
8.11.5.1. Custom Number Formatting¶
Format numbers using Java’s DecimalFormat patterns:
Formatted: $number.format('#,##0.00', $value)
If $value = 1234.5678, this produces: Output: `Formatted: 1,234.57`
8.11.5.2. Currency Formatting¶
Format numbers as currency:
Amount: $number.format('$#,##0.00', $amount)
If $amount = 1234.56, this produces: Output: `Amount: $1,234.56`
8.11.6. Best Practices¶
- Use appropriate tools for data types: Use the Number Tool for numeric formatting rather than trying to format numbers manually.
- Specify time zones explicitly: When working with dates, always specify the time zone to ensure consistent output across different environments.
- Combine tools for complex operations: Tools work well together - use Math Tool for calculations and Number Tool for formatting the results.
- Leverage conditional logic: Use #if statements to show different content based on your data.
- Format for your audience: Choose number and date formats that match your users’ expectations and locale.
These tools provide the foundation for creating dynamic, data-driven templates that can adapt to different contexts while maintaining consistent formatting and presentation.