Skip to content

Template helpers

The helpers a response body can use when the project renders responses as templates. The mock editor completes and checks the same list. How templates work, and what request offers, is in Dynamic responses with templates; fake names, addresses and numbers come from random, listed in Fake data.

Arguments after the helper name are positional; name=value arguments are named. Values in quotes are text, and a value in parentheses is another helper’s result: {{ date (parseDate request.headers.Date) }}.

Conditions and loops

if

Render the block when the condition is truthy; {{else}} for the alternative. Takes condition. A block helper: {{#if}}…{{/if}}.

{{#if request.query.debug}}on{{else}}off{{/if}}

unless

Render the block when the condition is falsy. Takes condition. A block helper: {{#unless}}…{{/unless}}.

{{#unless request.query.debug}}quiet{{/unless}}

each

Render the block once per item; this is the item, or name it with as |item|. Takes list. A block helper: {{#each}}…{{/each}}.

{{#each (range 1 3) as |n|}}{{ n }}{{/each}}

with

Render the block with the object as the context. Takes object. A block helper: {{#with}}…{{/with}}.

{{#with (parseJson request.body)}}{{ name }}{{/with}}

eq

True when both values are equal. Takes a, b. Inline, or as a block helper.

{{#eq request.method.name 'POST'}}created{{else}}read{{/eq}}

neq

True when the values differ. Takes a, b. Inline, or as a block helper.

{{#if (neq request.method.name 'GET')}}write{{/if}}

gt

True when a is greater than b. Takes a, b. Inline, or as a block helper.

{{#gt (size request.query.items) 3}}many{{/gt}}

gte

True when a is greater than or equal to b. Takes a, b. Inline, or as a block helper.

{{#if (gte (math request.query.page.first '+' 0) 2)}}later{{/if}}

lt

True when a is less than b. Takes a, b. Inline, or as a block helper.

{{#lt myVar 20}}less{{else}}more{{/lt}}

lte

True when a is less than or equal to b. Takes a, b. Inline, or as a block helper.

{{#if (lte (math request.query.page.first '+' 0) 1)}}first{{/if}}

Logic

and

True when every value is truthy. Takes a, b, …. Inline, or as a block helper.

{{#if (and request.query.a request.query.b)}}both{{/if}}

or

True when any value is truthy. Takes a, b, …. Inline, or as a block helper.

{{#if (or request.query.a request.query.b)}}either{{/if}}

not

True when the value is falsy. Takes value. Inline, or as a block helper.

{{#if (not request.query.debug)}}quiet{{/if}}

contains

True when the text contains the value, or the array has it as an element. Takes text or array, value. Inline, or as a block helper.

{{#if (contains request.body 'search')}}found{{/if}}

matches

True when the text matches the regex. Takes text, regex. Inline, or as a block helper.

{{#if (matches request.body '[0-9]+')}}numeric{{/if}}

Variables

assign

Assign the rendered block to a variable for later use. Takes variableName. A block helper: {{#assign}}…{{/assign}}.

{{#assign 'greeting'}}Hello {{ capitalize request.query.name }}{{/assign}}{{ greeting }}

val

Output a value, with a fallback when it is null, optionally assigning it to a variable. Takes value.

{{ val request.query.search }}
{{ val request.query.search or='default' }}
{{ val request.query.search default='default' }}
{{ val 10 assign='myVar' }}{{ myVar }}
{{ val request.query.search or='none' assign='search' }}

lookup

Read a key that Handlebars syntax cannot express in a path. Takes object, key.

{{ lookup request.query 'ids[].1' }}

Dates

now

Current date/time.

{{ now }}
{{ now format='yyyy-MM-dd' }}
{{ now offset='+3 days' }}
{{ now offset='-1 hours' format='HH:mm:ss' }}
{{ now timezone='UTC' }}
{{ now timezone='Europe/Warsaw' format='yyyy-MM-dd' }}
{{ now offset='+1 days' timezone='UTC' format='yyyy-MM-dd' }}

date

Format a date, usually one produced by parseDate or truncateDate. Takes date.

{{ date (parseDate request.headers.Date) }}
{{ date (parseDate request.headers.Date) format='yyyy-MM-dd' }}
{{ date (parseDate request.headers.Date) offset='+1 days' }}
{{ date (parseDate request.headers.Date) offset='+1 days' format='yyyy-MM-dd' }}
{{ date (parseDate request.headers.Date) timezone='UTC' format='HH:mm' }}

parseDate

Parse a date string; ISO 8601 and the RFC formats are detected without a format. Takes dateString.

{{ date (parseDate request.headers.Date) }}
{{ date (parseDate request.query.from format='dd/MM/yyyy') }}

truncateDate

Truncate a date, e.g. 'first day of month', 'first hour of day', 'last day of year'. Takes date, unit.

{{ date (truncateDate (parseDate request.headers.Date) 'first day of month') }}

Random values

randomValue

Generate random string value.

{{ randomValue }}
{{ randomValue length=10 }}
{{ randomValue type='UUID' }}
{{ randomValue length=8 type='ALPHABETIC' }}
{{ randomValue length=8 type='ALPHABETIC' uppercase=true }}
{{ randomValue uppercase=true }}

randomInt

Random integer in range.

{{ randomInt }}
{{ randomInt lower=1 upper=100 }}

randomDecimal

Random decimal number in range.

{{ randomDecimal }}
{{ randomDecimal lower=0.0 upper=1.0 }}

pickRandom

Pick a random item from the values, or from a list given as the only value. Takes value, value, ….

{{ pickRandom 'a' 'b' 'c' }}
{{ pickRandom 1 2 3 4 5 count=3 }}

Numbers

math

Arithmetic with '+', '-', '*', '/' or '%'. Takes a, operator, b.

{{ math request.query.a '+' request.query.b }}
{{ math 10 '*' 5 }}
{{ math 100 '/' 4 }}
{{ math 17 '%' 5 }}

numberFormat

Format a number; format is 'integer', 'currency', 'percent' or a pattern like '###.00'. Takes number, format?, locale?.

{{{ numberFormat 123.4567 'currency' 'en_GB' }}}
{{{ numberFormat 1234.567 maximumFractionDigits=2 minimumFractionDigits=2 }}}
{{{ numberFormat 1234.567 maximumIntegerDigits=3 minimumIntegerDigits=3 }}}
{{{ numberFormat 12345.678 groupingUsed=false }}}
{{{ numberFormat 1.239 roundingMode='down' maximumFractionDigits=2 }}}

isOdd

'odd', or the class name, when the number is odd. Takes number, className?.

{{ isOdd @index 'alt-row' }}

isEven

'even', or the class name, when the number is even. Takes number, className?.

{{ isEven @index 'alt-row' }}

stripes

The even or odd class name for the number. Takes number, evenClass, oddClass.

{{ stripes @index 'row-even' 'row-odd' }}

Lists

range

The integers from start to end, for iteration. Takes start, end.

{{#each (range 1 5)}}{{ this }}{{/each}}

array

An array of the given values. Takes value, value, ….

{{#each (array 'a' 'b' 'c')}}{{ this }}{{/each}}

arrayAdd

The array with the value added, at the end unless a position is given. Takes array, value.

{{ arrayAdd (array 1 'three') 2 }}
{{ arrayAdd (array 1 'three') 2 position='start' }}

arrayRemove

The array with one element removed, the last unless a position is given. Takes array.

{{ arrayRemove (array 1 2 'three') }}
{{ arrayRemove (array 1 2 'three') position=1 }}

arrayJoin

Join values with a separator; as a block, render each item with as |item|. Takes separator, array or values. Inline, or as a block helper.

{{ arrayJoin ', ' (array 'One' 'Two' 'Three') }}
{{ arrayJoin ',' (array 1 2 3) prefix='[' suffix=']' }}

size

The length of a string, list or map. Takes value.

{{ size (jsonPath request.body '$.items') }}

join

Join array with delimiter. Takes array, delimiter.

{{ join (jsonPath request.body '$.items') ', ' }}

storeList

The records of a data store collection as a list, oldest first; empty until a mock saves one. Takes store.collection.

{{{toJson (storeList store.users)}}}

storeQuery

A list endpoint over a data store collection: filters on the listed fields by the caller's query parameters, sorts, pages and counts; gives items, total, page, size and pages (read size as this.size) Takes store.collection, request.query.

{{{toJson (lookup (storeQuery store.users request.query filter='status' sort='name') 'items')}}}
{{#with (storeQuery store.users request.query filter='status,role' sort='name,createdAt' defaultSort='-createdAt' pageSize=20 maxPageSize=100)}}{{{toJson items}}}{{/with}}

JSON

parseJson

Parse JSON text into an object, optionally assigned to a variable. Takes json, variableName?. Inline, or as a block helper.

{{ parseJson request.body 'bodyJson' }}{{ bodyJson.name }}

toJson

Write a value as JSON. Takes value.

{{ toJson (array 1 2 3) }}

formatJson

Pretty-print or compact JSON, given as an argument or as the block. Takes json?. Inline, or as a block helper.

{{ formatJson request.body }}
{{#formatJson format='compact'}}{ "a": 1 }{{/formatJson}}

jsonPath

Extract a value with a JSONPath expression. Takes json, jsonPath.

{{ jsonPath request.body '$.items[0].name' }}
{{ jsonPath request.body '$.optional' default='N/A' }}

jsonArrayAdd

The JSON array with an item added, given as an argument or as the block. Takes array, item?. Inline, or as a block helper.

{{#jsonArrayAdd existingArray}}{ "id": 321 }{{/jsonArrayAdd}}
{{#jsonArrayAdd existingArray maxItems=2}}{ "id": 456 }{{/jsonArrayAdd}}
{{#jsonArrayAdd existingArray flatten=true}}[{ "id": 456 }]{{/jsonArrayAdd}}
{{ jsonArrayAdd existingArray itemToAdd jsonPath='$[0].names' }}

jsonMerge

Deep-merge a second JSON object, given as an argument or as the block, into the first. Takes object, other?. Inline, or as a block helper.

{{ jsonMerge object1 object2 }}
{{#jsonMerge object1 removeNulls=true}}{ "removeMe": null }{{/jsonMerge}}

jsonRemove

Remove the elements or attributes a JSONPath expression selects. Takes json, jsonPath.

{{ jsonRemove existingArray '$.[?(@.id == 123)]' }}

jsonSort

Sort a JSON array by the values a JSONPath expression selects. Takes array, jsonPath.

{{ jsonSort jsonArray '$[*].name' }}
{{ jsonSort jsonArray '$[*].id' order='desc' }}
{{ jsonSort jsonArray '$[*].name' nulls='last' }}
{{ jsonSort jsonArray '$[*].name' order='asc' nulls='first' }}

XML

formatXml

Pretty-print or compact XML, given as an argument or as the block. Takes xml?. Inline, or as a block helper.

{{ formatXml request.body }}
{{#formatXml format='compact'}}<a><b/></a>{{/formatXml}}

xPath

Extract a value with an XPath expression; nodes expose name, text and attributes. Takes xml, xpath.

{{ xPath request.body '/root/item/text()' }}

soapXPath

Extract a value from a SOAP body with an XPath expression. Takes soapXml, xpath.

{{ soapXPath request.body '/a/test/text()' }}

Text

upper

Upper-case the text. Takes text.

{{ upper request.query.code }}

lower

Lower-case the text. Takes text.

{{ lower request.headers.X-Name }}

capitalize

Capitalise every word. Takes text.

{{ capitalize request.query.search }}

capitalizeFirst

Capitalise the first character. Takes text.

{{ capitalizeFirst request.query.search }}

trim

Trim whitespace from an argument or the block. Takes text?. Inline, or as a block helper.

{{ trim request.headers.X-Padded }}

abbreviate

Shorten the text to maxWidth characters with an ellipsis. Takes text, maxWidth.

{{ abbreviate request.body 40 }}

substring

The characters between start and end. Takes text, start, end?.

{{ substring request.query.code 0 3 }}

replace

Replace text in string. Takes text, old, new.

{{ replace request.body 'old' 'new' }}

slugify

Lower-case, hyphen-separated form of the text. Takes text.

{{ slugify request.query.title }}

stripTags

Remove HTML tags. Takes html.

{{ stripTags request.body }}

stringFormat

Insert the values into a format string such as '%s has %d items'. Takes format, value, ….

{{ stringFormat 'Hello %s' request.query.name }}

defaultIfEmpty

The value, or the default when it is empty. Takes value, default.

{{ defaultIfEmpty request.query.page '1' }}

yesno

'yes', 'no' or 'maybe' for true, false and null. Takes value.

{{ yesno request.query.active }}
{{ yesno request.query.active yes='on' no='off' maybe='unknown' }}

regexExtract

The first match of a regex; with a variable name, the capture groups become variable.0, variable.1, …. Takes text, regex, variableName?.

{{ regexExtract request.body '[A-Z]{3}-[0-9]{4}' }}
{{ regexExtract request.body '([a-z]+)-([0-9]+)' 'parts' }}{{ parts.0 }}
{{ regexExtract request.body '[0-9]+' default='none' }}

Encoding

base64

Base64 encode, or decode, an argument or the block. Takes text?. Inline, or as a block helper.

{{ base64 request.body }}
{{ base64 request.headers.X-Encoded decode=true }}
{{#base64 padding=false}}Content to encode{{/base64}}

urlEncode

URL encode, or decode, an argument or the block. Takes text?. Inline, or as a block helper.

{{ urlEncode request.query.param }}
{{ urlEncode request.query.param decode=true }}

formData

Parse URL-encoded form data, inside a with block or assigned to a name; each field is a list, so read it with .first. Without urlDecode=true values keep their percent-encoding. Takes formText.

{{#with (formData request.body)}}{{field.first}}{{/with}}
{{#with (formData request.body urlDecode=true)}}{{field.first}}{{/with}}
{{ formData request.body 'form' urlDecode=true }}{{form.field.first}}

Tokens

jwt

A token signed with the project's key. Add claims as named arguments; iat, exp, jti and iss (the caller's address) are filled in unless given. Needs a plan with the identity provider. Takes claims?.

{{ jwt sub='user-1' aud='my-api' }}
{{ jwt sub='user-1' expiresIn=3600 }}
{{ jwt sub='user-1' alg='ES256' }}
{{ jwt sub='user-1' typ='at+jwt' }}
{{ jwt sub='user-1' notBefore=60 }}

jwks

The project's published signing keys as a JWKS document, for a /.well-known/jwks.json mock. Needs a plan with the identity provider.

{{ jwks }}

jwtClaim

A claim of a token this project signed; a leading 'Bearer ' is dropped. A foreign, altered or expired token gives the default, and without one the response fails. Takes token, claim.

{{ jwtClaim request.headers.Authorization 'sub' default='anonymous' }}
{{ jwtClaim request.headers.Authorization 'scope' typ='at+jwt' default='' }}

storeQuery answers a list endpoint over one data store collection: it filters, sorts and pages the records by the caller’s query parameters, and counts them. A REST resource uses it in its list mock.

{{#with
(storeQuery
store.users
request.query
filter='status,role'
sort='name,createdAt'
defaultSort='-createdAt'
pageSize=20
maxPageSize=100
)
}}{"data":
{{{toJson items}}}, "meta": {"total":
{{total}}, "page":
{{page}}, "size":
{{this.size}}, "pages":
{{pages}}
} }{{/with}}

The first argument is the collection, store.<collection>; the second is request.query. The rest are named:

Argument Takes
filter The fields callers may filter by, comma-separated: at most 20, each a path of one to five names, such as address.city
sort The fields callers may sort by: at most 10
defaultSort The order without ?sort=, such as -createdAt. Without it, the order records were first saved in
pageSize The page size without ?size=. 20 by default
maxPageSize The largest ?size= honoured; a larger one is cut to it. 100 by default, at most 1,000
style 'offset' to page with ?offset= and ?limit= instead of ?page= and ?size=
where, equals Keep only records whose field equals a value, such as where='userId' equals=request.path.userId for a nested resource
pageParam, sizeParam, offsetParam, limitParam, sortParam The caller’s names for the paging and sort parameters, when they are not page, size, offset, limit and sort

It gives items (the page of records), total (how many match the filters), count (how many are on this page), and page, size and pages, or with style='offset', offset and limit. Read the size as {{this.size}}: a bare {{size}} is the size helper. Without a data store on the plan, the collection is absent and the helper answers an empty page.

Query Does
?status=active Keeps records whose status equals active
?status=active&status=new Keeps records whose status is either
?price_gt=10 _gt, _gte, _lt, _lte and _ne compare; _like keeps values that contain the text, ignoring case
?sort=name,-createdAt Sorts by up to two listed fields; a leading - sorts descending
?page=2&size=50 Pages; or ?offset=50&limit=50 with style='offset'

A parameter that names no listed field is ignored, so an unknown parameter or a cache-buster never empties the list. When a listed field itself ends in _gt or another suffix, the exact name wins.

  • Two values compare as numbers when both read as numbers, and otherwise as text, character by character, so B sorts before a. A sort puts numbers before text.
  • A field that is missing, null, an object or a list matches only _ne, and sorts last.
  • A page or size from the caller that is not a number falls back to the default, and one out of range is cut to the nearest allowed value, rather than failing. A wrong template fails the render: an unknown argument, a field that is not a plain path, or a first argument that is not a collection.

storeQuery reads the whole collection on every request. It reads the first 64 filter values of a request, taking parameters in name order, and ignores the rest. Each record it reads counts as one of the 10,000 repetitions a response’s templates may make, and the page it returns counts toward the characters they may write. 5,000 records of 800 bytes, with two filters and a sort, take about 4 milliseconds a call. It reads one collection, joins nothing, searches no text and offers no cursor.

Report a problem with this page