Docs »

Bots »

Scripting »

Reference: Filters

These filters are available in bot scripts and snippets:

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!

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=

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

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:



{{"This has 😂 emoji"|convert_encoding('iso-8859-1', 'utf-8')}}


This has ? emoji

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}}


16 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 &quot;escaped&quot; for &lt;b&gt;HTML&lt;/b&gt;

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 an keyed-hash 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.

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?

md5

Generate an MD52 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
    }
}

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 expressions3 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-14 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 remove
  • side
    • 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

  1. Wikipedia: Hash-based message authentication code (HMAC) - https://en.wikipedia.org/wiki/Hash-based_message_authentication_code 

  2. Wikipedia: MD5 - https://en.wikipedia.org/wiki/MD5 

  3. Wikipedia: Regular Expression - https://en.wikipedia.org/wiki/Regular_expression 

  4. Wikipedia: SHA-1 - https://en.wikipedia.org/wiki/SHA-1