These filters are available in bot scripts and snippets:
- abs
- alphanum
- array_sum
- base_convert
- base64_decode
- base64_encode
- base64url_decode
- base64url_encode
- batch
- bytes_pretty
- capitalize
- cerb_translate
- context_name
- convert_encoding
- csv
- date
- date_modify
- date_pretty
- default
- escape
- first
- format
- hash_hmac
- image_info
- indent
- join
- json_encode
- json_pretty
- keys
- last
- length
- lower
- markdown_to_html
- md5
- merge
- nl2br
- number_format
- parse_emails
- permalink
- quote
- regexp
- replace
- reverse
- round
- secs_pretty
- sha1
- slice
- sort
- split
- split_crlf
- split_csv
- striptags
- title
- trim
- truncate
- unescape
- upper
- url_decode
- url_encode
abs
Return the absolute value of a number:
{{-5|abs}}
5
alphanum
Remove non-alphanumeric characters from a string:
{{"* Ignore spaces and non-alphanumeric characters+1$2%3!"|alphanum}}
Ignorespacesandnonalphanumericcharacters123
Also allow specific characters:
{{"* Ignore non-alphanumeric but allow spaces$%#!"|alphanum(' !')}}
Ignore nonalphanumeric but allow spaces!
array_sum
Sum the numeric elements of an array.
{{array_sum([1,2,3,4,5])}}
15
base_convert
Convert between number system bases.
(Introduced in 9.0.8)
{% set int = 123456789 %}
{{int|base_convert(10,16)}}
{% set hex = '75bcd15' %}
{{hex|base_convert(16,10)}}
75bcd15
123456789
base64_decode
Decode a base64-encoded string:
{% set b64 = "VGhpcyB3YXMgYmFzZTY0LWVuY29kZWQ=" %}
{{b64|base64_decode}}
This was base64-encoded
base64_encode
Encode a string in base64:
{{"This was base64-encoded"|base64_encode}}
VGhpcyB3YXMgYmFzZTY0LWVuY29kZWQ=
base64url_decode
(Added in 9.1.8)
Decode a base64url-encoded string:
{% set b64 = "VGhpcyB3YXMgYmFzZTY0dXJsLWVuY29kZWQ" %}
{{b64|base64url_decode}}
This was base64url-encoded
base64url_encode
(Added in 9.1.8)
Encode a string in base64url:
{{"This was base64url-encoded"|base64url_encode}}
VGhpcyB3YXMgYmFzZTY0dXJsLWVuY29kZWQ
batch
Break a list into smaller chunks with batch:
{% set items = ['red','blue','green'] %}
{{items|batch(2, '(empty)')|json_encode|json_pretty}}
[
[
"red",
"blue"
],
[
"green",
"(empty)"
]
]
bytes_pretty
Convert a number into a human readable number of bytes:
{{"123456789"|bytes_pretty(2)}}
123.46 MB
The optional argument determines the number of digits of precision.
capitalize
Capitalize the first character of a string (and lowercase the rest):
{% set first_name = "kina" %}
{{first_name|capitalize}}
Kina
cerb_translate
(Added in 9.0)
Converts string IDs (like status.open
) into text in the current worker’s language.
The ticket is {{'status.open'|cerb_translate}}
The ticket is open.
context_name
Convert a Cerb context
ID into a human readable label:
{{'cerberusweb.contexts.ticket'|context_name('singular')}}
{{'cerberusweb.contexts.task'|context_name('plural')}}
tickets
task
convert_encoding
Convert character encodings to the first argument from the second. If the second argument is blank then Cerb will attempt to auto-detect the current encoding.
{{"This has 😂 emoji"|convert_encoding('iso-8859-1', 'utf-8')}}
This has ? emoji
csv
(Added in 9.6.4)
Format an array as a comma-separated values list. This is useful for exporting reports for Excel from bots.
{% set records = [
{
id: 1,
subject: "Help with the API",
},
{
id: 2,
subject: "Automating email replies",
}
] %}
ID,Subject
{{records|csv}}
ID,Subject
1,"Help with the API"
2,"Automating email replies"
date
Use the date filter to format a string or variable as a date:
{{'now'|date('F d, Y h:ia T')}}
{{'tomorrow 5pm'|date('D, d F Y H:i T')}}
{{'+2 weeks 08:00'|date('Y-m-d h:ia T')}}
December 12, 2017 11:50am PST
Wed, 13 December 2017 17:00 PST
2017-12-26 08:00am PST
The second parameter to the date filter can specify a timezone to use:
{% set ts_now = 'now' -%}
Bangalore: {{ts_now|date(time_format, 'Asia/Calcutta')}}
Berlin: {{ts_now|date(time_format, 'Europe/Berlin')}}
New York: {{ts_now|date(time_format, 'America/New_York')}}
Bangalore: December 13, 2017 01:27
Berlin: December 12, 2017 20:57
New York: December 12, 2017 14:57
You can get a Unix timestamp (seconds since 1-Jan-1970 00:00:00 UTC) from a date value with the |date('U')
filter:
It has been {{'now'|date('U')}} seconds since {{'0'|date(null, 'UTC')}}
It has been 1513108417 seconds since January 1, 1970 00:00
date_modify
If you need to manipulate a date, create a date object with the date function and use the date_modify filter:
{% set format = 'D, d M Y T' %}
{% set timestamp = date('now') %}
Now: {{timestamp|date(format)}}
+2 days: {{timestamp|date_modify('+2 days')|date(format)}}
Now: Tue, 12 Dec 2017 PST
+2 days: Thu, 14 Dec 2017 PST
date_pretty
Convert a Unix timestamp into a human-readable, relative date:
{% set timestamp = date("Jan 9 2002 10am", "America/Los_Angeles") %}
{{timestamp|date('U')|date_pretty}}
18 years ago
default
You can use the default filter to give a default value to empty variables:
{% set name = '' %}
Hi {{name|default('there')}}
Hi there
escape
Escape strings and variables with the following modes:
html
js
css
url
html_attr
{{'This is "escaped" for Javascript'|escape('js')}}
{{'This is "escaped" for <b>HTML</b>'|e('html')}}
This\x20is\x20\x22escaped\x22\x20for\x20Javascript
This is "escaped" for <b>HTML</b>
first
Return the first item of an array, object, or string:
{% set items = [1,2,3] %}
{{items|first}}
1
format
Insert variables into a string:
{% set who = "Kina" %}
{% set quantity = 120 %}
{{"%s closed %d tickets today!"|format(who, quantity)}}
Kina closed 120 tickets today!
hash_hmac
Generate a hash-based message authentication code (HMAC1) using a secret key.
For instance, you can use this to sign parameters in a survey URL to verify that the recipient didn’t modify them.
{% set data = {'email': 'kina@cerb.example', 'survey_id': 123} %}
{{data|json_encode|hash_hmac("THIS IS SECRET","sha256")}}
5514f8aed3b39159d455f9a8f74b5d23d4f96391fa4a27d1bea6f940cb7d410f
Provide your own value for THIS IS SECRET. You an store it in the bot configuration.
image_info
(Added in 9.6.7)
Returns information about an image. The image may be provided as bytes or in data URI format.
|image_info()
{% set image_string %}
data:image/png;base64,iVBORw0KGgoAAAA....
{% endset %}
{{image_string|image_info|json_encode|json_pretty}}
{
"width": 100,
"height": 100,
"channels": 3,
"bits": 8,
"type": "image/png"
}
indent
(Added in 9.6.4)
Prefix the start of each line with a given marker in a block of text.
|indent(marker, start_line)
marker | The prefix to add to the beginning of each line. |
start_line | The line number to start prefixing from (0-based). |
{% set text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget diam
eu orci hendrerit elementum. Suspendisse egestas, dolor at efficitur sollicitudin, magna eros
scelerisque risus, at tincidunt massa augue a eros. Nullam scelerisque luctus suscipit. Sed
dui metus, rhoncus sed diam non, pretium maximus augue. Phasellus feugiat justo mi, in
tristique quam euismod pellentesque. Curabitur ut libero sagittis sem semper ultrices. Nullam
et mi id arcu vulputate fringilla ut quis nibh. Fusce lobortis magna eu quam porta scelerisque.
Suspendisse maximus fringilla tellus, a pellentesque sem tincidunt sit amet." -%}
{{text|indent('> ')}}
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget diam
> eu orci hendrerit elementum. Suspendisse egestas, dolor at efficitur sollicitudin, magna eros
> scelerisque risus, at tincidunt massa augue a eros. Nullam scelerisque luctus suscipit. Sed
> dui metus, rhoncus sed diam non, pretium maximus augue. Phasellus feugiat justo mi, in
> tristique quam euismod pellentesque. Curabitur ut libero sagittis sem semper ultrices. Nullam
> et mi id arcu vulputate fringilla ut quis nibh. Fusce lobortis magna eu quam porta scelerisque.
> Suspendisse maximus fringilla tellus, a pellentesque sem tincidunt sit amet.
join
Convert an array to a string with delimiters:
{% set items = [1,2,3] %}
{{items|join(',')}}
{{items|join(' ')}}
1,2,3
1 2 3
json_encode
You can encode any variable as a JSON string with the json_encode filter:
{% set json = {'name': 'Joe Customer'} %}
{% set json = dict_set(json, 'order_id', 54321) %}
{% set json = dict_set(json, 'status.text', 'shipped') %}
{% set json = dict_set(json, 'status.tracking_id', 'Z1F238') %}
{{json|json_encode}}
{"name":"Joe Customer","order_id":54321,"status":{"text":"shipped","tracking_id":"Z1F238"}}
json_pretty
You can “prettify” a JSON string with the json_pretty filter:
{% set json = {'name': 'Joe Customer'} %}
{% set json = dict_set(json, 'order_id', 54321) %}
{% set json = dict_set(json, 'status.text', 'shipped') %}
{% set json = dict_set(json, 'status.tracking_id', 'Z1F238') %}
{{json|json_encode|json_pretty}}
{
"name": "Joe Customer",
"order_id": 54321,
"status": {
"text": "shipped",
"tracking_id": "Z1F238"
}
}
keys
Return the keys of an array or object:
{% set list = ['red','green','blue'] %}
{% set obj = { 'name': 'Kina', 'age': 35, 'title': 'Customer Support Supervisor'} %}
{{list|keys|join(',')}}
{{obj|keys|json_encode}}
0,1,2
["name","age","title"]
last
Return the last item of an array, object, or string:
{% set items = [1,2,3] %}
{{items|last}}
3
length
Return the length of a string or array:
{{"This is a string"|length}}
{{[1,2,3,4,5]|length}}
16
5
lower
Convert a string to lowercase:
{{"WHY ARE YOU YELLING?"|lower}}
why are you yelling?
markdown_to_html
(Added in 9.5.4)
Convert Markdown2 formatting to HTML:
{% set markdown %}
This is **bold** text with a [link](https://cerb.ai/)
{% endset %}
{{markdown|markdown_to_html}}
<p>This is <strong>bold</strong> text with a <a href="https://cerb.ai/">link</a></p>
md5
Generate an MD53 hash for a string:
{{"You can verify this hash"|md5}}
1c20552e3bae1c4711cf697137002581
merge
Combine two arrays or objects:
{% set mfgs = ['Tesla','Ford'] %}
{% set mfgs = mfgs|merge(['Toyota','GM']) %}
{{mfgs|json_encode}}
["Tesla","Ford","Toyota","GM"]
nl2br
Convert newline characters (\n
) to HTML breaks (<br />
):
{% set text = "This has
line feeds
in the text
"%}
{{text|nl2br}}
This has<br />
line feeds<br />
in the text<br />
number_format
Format a number with thousand separators and decimal places:
{% set cost = 16858 %}
That will be ${{cost|number_format(2,'.',',')}}
That will be $16,858.00
parse_emails
Parse a delimited string of email addresses into an object. This also assists with email validation.
{% set emails = "kina@cerb.example, milo@cerb.example, karl" %}
{{emails|parse_emails|json_encode|json_pretty}}
{
"kina@cerb.example": {
"full_email": "kina@cerb.example",
"email": "kina@cerb.example",
"mailbox": "kina",
"host": "cerb.example",
"personal": null
},
"milo@cerb.example": {
"full_email": "milo@cerb.example",
"email": "milo@cerb.example",
"mailbox": "milo",
"host": "cerb.example",
"personal": null
},
"karl@localhost": {
"full_email": "karl@localhost",
"email": "karl@localhost",
"mailbox": "karl",
"host": "localhost",
"personal": null
}
}
permalink
(Added in 9.2.3)
{% set text = "This is the title of a record!" %}
{{text|permalink|lower}}
this-is-the-title-of-a-record
quote
{% set text = "This is a message you are replying to.
You should quote it.
" %}
{{text|quote}}
> This is a message you are replying to.
>
> You should quote it.
regexp
You can use regular expressions4 with the regexp filter to match or extract patterns.
|regexp(pattern,group)
pattern
The regular expression pattern to match.group
: The matching group()
from the pattern to extract as a string.
Example:
{% set text = "Your Amazon Order #Z-1234-5678-9 has shipped!" %}
{% set order_id = text|regexp("/Amazon Order #([A-Z0-9\-]+)/", 1) %}
Amazon Order #: {{order_id}}
Amazon Order #: Z-1234-5678-9
If you need to escape characters in your regexp pattern, you should use a set block rather than a string:
{% set pattern %}
#\[.*?\] (.*)#
{% endset %}
{% set bracketed_text = "[ABC-123-45678] Order Processing - 7 Days" %}
{{bracketed_text|regexp(pattern, 1)}}
Order Processing - 7 Days
replace
{{"I really like %food%"|replace({'%food%':'ice cream'})}}
I really like ice cream
reverse
Reverse a string or array:
{{"Leonardo da Vinci"|reverse}}
{{[1,2,3,4,5]|reverse|join}}
icniV ad odranoeL
54321
The optional preserve_keys parameter will maintain object keys.
round
Round a number with desired precision.
|round(precision,method)
precision
The number of floating point digits.method
:- common
- ceil
- floor
{% set pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286 %}
{{pi|round}}
{{pi|round(5)}}
{{pi|round(5,'ceil')}}
3
3.14159
3.1416
secs_pretty
{{"300"|secs_pretty}}
{{"86400"|secs_pretty}}
{{"604800"|secs_pretty()}}
5 mins
1 day
1 week
sha1
Generate an SHA-15 hash for a string:
{{"You can verify this hash"|sha1}}
50ae61a375994fd178cd47fc7d29f7ec5724dda3
slice
Extract part of a string, array, or object.
|slice(start, length, preserve_keys)
{{[1,2,3,4,5]|slice(2,2)|json_encode}}
{{"This is some text"|slice(0,4)}}
[3,4]
This
sort
Sort an array:
{% set x = [9,5,1,6,4,3] %}
{{x|sort|slice(0,6)|json_encode}}
[1,3,4,5,6,9]
split
Convert a string to an array with the given delimiter.
|split(delimiter, limit)
{{"1,2,3,4,5"|split(',')|json_encode}}
["1","2","3","4","5"]
split_crlf
Split a string on any combination of carriage return (\r
) and linefeed (\n
) delimiters.
{% set rainbow = "red
orange
yellow
green
blue
indigo
violet" %}
{{rainbow|split_crlf|json_encode}}
["red","orange","yellow","green","blue","indigo","violet"]
split_csv
Split a string on comma delimiters. This automatically handles whitespace padding.
{% set coins = "BTC, ETH ,LTC" %}
{{coins|split_csv|json_encode}}
["BTC","ETH","LTC"]
striptags
Remove HTML tags from a string.
{% set html = "This <b>string</b> has <b>HTML</b> tags!" %}
{{html|striptags}}
This string has HTML tags!
title
{% set book_title = "the ultimate bot builder handbook" %}
{{book_title|title}}
The Ultimate Bot Builder Handbook
trim
Remove leading and/or trailing whitespace from a string.
|trim(character_mask, side)
character_mask
The characters to removeside
- both
- left
- right
{% set str = " whitespace " %}
{{str|trim}}
{{str|trim(' ', 'left')}}
{{str|trim(' ', side='right')}}
whitespace
whitespace
whitespace
truncate
Ensure that a string is no longer than the given limit.
|truncate(limit)
{% set str = "This string is longer than we'd prefer" %}
{{str|truncate(11)}}
This string...
unescape
Decode HTML entities:
{{""iPhone" is © Apple, Inc."|unescape}}
"iPhone" is © Apple, Inc.
upper
Convert a string to uppercase:
{{"I can't hear you!"|upper}}
I CAN'T HEAR YOU!
url_decode
Decode a URL query string into an array:
{% set query = "name=Kina&action=light_on" %}
{{query|url_decode('json')}}
{"name":"Kina","action":"light_on"}
url_encode
Build a URL query string from an array:
{% set args = {"name": "Kina", "action": "light_on" } %}
{{args|url_encode}}
name=Kina&action=light_on
References
-
Wikipedia: Hash-based message authentication code (HMAC) - https://en.wikipedia.org/wiki/Hash-based_message_authentication_code ↩
-
Wikipedia: Markdown - https://en.wikipedia.org/wiki/Markdown ↩
-
Wikipedia: MD5 - https://en.wikipedia.org/wiki/MD5 ↩
-
Wikipedia: Regular Expression - https://en.wikipedia.org/wiki/Regular_expression ↩
-
Wikipedia: SHA-1 - https://en.wikipedia.org/wiki/SHA-1 ↩