$calc (beta)
The $calc function is a powerful expression evaluator that enables complex calculations, string manipulations, array operations, and provides a secure sandbox environment within your templates.
Basic Usage
{{$calc "5 + 3"}} {{!-- outputs: 8 --}}
{{$ "5 + 3"}} {{!-- shorthand syntax --}}
Output Types
The function can return different types of values:
Numbers: Mathematical calculations, statistical results
Strings: Text manipulation results
Arrays: Collection operations
Booleans: Conditional evaluations
Empty String: Returned for null/undefined values or errors
Variable Interpolation
Use {variableName}
syntax to reference context variables:
{{$calc "{price} * 1.2"}} {{!-- outputs: 120 --}}
{{$calc "{user.age} + 5"}} {{!-- outputs: 30 --}}
Storing Results
You can store calculation results for later use using the $var
function:
{{$var "tax_amount" ($calc "{price} * 0.2")}}
{{!-- Later in the template --}}
Total with tax: {{$calc "{price} + {tax_amount}"}}
Formatting Options
Decimal Places
{{$calc "100 / 3" decimals=2}} {{!-- outputs: 33.33 --}}
Custom Number Format (using number formatter patterns)
{{$calc "1234.5" format="0,0.00"}} {{!-- outputs: 1,234.50 --}}
{{$calc "0.123" format="0.00%"}} {{!-- outputs: 12.30% --}}
Error Handling
{{$calc "10/0" error="Division Error"}} {{!-- outputs: "Division Error" --}}
Function Reference
Mathematical Functions
Basic Arithmetic
Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulo (%)
{{$calc "5 + 3"}} {{!-- addition: 8 --}}
{{$calc "5 - 3"}} {{!-- subtraction: 2 --}}
{{$calc "5 * 3"}} {{!-- multiplication: 15 --}}
{{$calc "15 / 3"}} {{!-- division: 5 --}}
{{$calc "5 % 2"}} {{!-- modulo: 1 --}}
Advanced Math Functions
abs(x): Returns absolute value of x
{{$calc "abs(-5)"}} {{!-- absolute value: 5 --}}
max(...args): Returns largest value among arguments
{{$calc "max(1, 2, 3)"}} {{!-- maximum value: 3 --}}
min(...args): Returns smallest value among arguments
{{$calc "min(1, 2, 3)"}} {{!-- minimum value: 1 --}}
pow(base, exp): Returns base raised to exp power
{{$calc "pow(2, 3)"}} {{!-- power: 8 --}}
sqrt(x): Returns square root of x
{{$calc "sqrt(16)"}} {{!-- square root: 4 --}}
round(x): Rounds to nearest integer
{{$calc "round(3.7)"}} {{!-- round: 4 --}}
ceil(x): Rounds up to nearest integer
{{$calc "ceil(3.2)"}} {{!-- ceiling: 4 --}}
floor(x): Rounds down to nearest integer
{{$calc "floor(3.8)"}} {{!-- floor: 3 --}}
String Operations
lower(str): Converts string to lowercase
{{$calc 'lower("HELLO")'}} {{!-- lowercase: "hello" --}}
upper(str): Converts string to uppercase
{{$calc 'upper("hello")'}} {{!-- uppercase: "HELLO" --}}
trim(str): Removes leading/trailing whitespace
{{$calc 'trim(" hello ")'}} {{!-- trim whitespace: "hello" --}}
concat(...args): Joins all arguments into single string
{{$calc 'concat("a", "b")'}} {{!-- concatenate: "ab" --}}
slice(str, start, end): Extracts portion of string
{{$calc 'slice("hello", 0, 2)'}} {{!-- slice string: "he" --}}
replace(str, search, replace): Replaces first occurrence of search with replace
{{$calc 'replace("hello", "l", "w")'}} {{!-- replace: "hewlo" --}}
Array Operations
arr(...args): Creates array from arguments
{{$calc "arr(1, 2, 3)"}} {{!-- create array: [1, 2, 3] --}}
first(arr): Returns first element
{{$calc "first([1, 2, 3])"}} {{!-- first element: 1 --}}
last(arr): Returns last element
{{$calc "last([1, 2, 3])"}} {{!-- last element: 3 --}}
len(arr): Returns array length
{{$calc "len([1, 2, 3])"}} {{!-- array length: 3 --}}
join(arr, separator, finalSeparator): Joins array elements with optional custom separators
{{$calc 'join(["a","b"], ",")'}} {{!-- join array: "a,b" --}}
split(str, separator): Splits string into array
{{$calc 'split("a,b", ",")'}} {{!-- split string: ["a", "b"] --}}
sort(arr): Returns sorted array
{{$calc "sort([3, 1, 2])"}} {{!-- sort array: [1, 2, 3] --}}
reverse(arr): Returns reversed array
{{$calc "reverse([1, 2, 3])"}} {{!-- reverse array: [3, 2, 1] --}}
Statistical Functions
avg(...nums): Calculates average of numbers
{{$calc "avg(1, 2, 3)"}} {{!-- average: 2 --}}
med(nums): Calculates median of array
{{$calc "med([1, 3, 2])"}} {{!-- median: 2 --}}
sum(nums, [prop]): Sums array elements, optionally extracting property from objects
{{$calc "sum([1, 2, 3])"}} {{!-- sum: 6 --}}
{{!-- Sum with object arrays --}}
{{$calc 'sum([{val: 1}, {val: 2}], "val")'}} {{!-- sum of val property: 3 --}}
Type Conversion
str(val): Converts to string
{{$calc 'str(123)'}} {{!-- to string: "123" --}}
num(val): Converts to number
{{$calc 'num("123")'}} {{!-- to number: 123 --}}
bool(val): Converts to boolean
{{$calc 'bool(1)'}} {{!-- to boolean: true --}}
Complex Examples
Data Processing Pipeline
{{!-- Store processed data for later use --}}
{{$var "processed_data" ($calc 'join(sort(arr(concat(upper("hello"), ":", str(sum([1,2,3]))),concat(lower("WORLD"), ":", str(avg(2,4,6)))))," | ")')}}
{{!-- Output: "HELLO:6 | world:4" --}}
{{processed_data}}
Complex Conditional Calculation
{{$calc 'if(len({items}) > 0) then concat("Items: ", join(sort(arr(concat(upper(first({items})), "-", str(sum({values}))), concat(lower(last({items})), "-", str(avg({values})))) ), " | ")) else "No items available" endif'}}
Limitations and Safety Features
Maximum number size: 1e15
Maximum array length: 1000
Best Practices
Store intermediate calculations using $var for complex operations
Use appropriate formatting options for consistent output
Handle potential errors with the error option
Break complex calculations into smaller parts
Use meaningful variable names
Consider performance with large arrays
Validate user input before processing
Use comments to document complex expressions
Last updated
Was this helpful?