Home platformOS Logo

Liquid - platformOS Liquid Filters

Last edit: Apr 23, 2020

Liquid filters in platformOS

In platformOS you can use all standard Liquid filters. Besides standard Liquid filters, you can also use platformOS-specific Liquid filters we added.

add_hash_key(aliases: assign_to_hash_key)

Returns: Hash

Params

  • hash (Hash)
  • key (String)
  • value (Object)

Examples


        {% assign accountants = "Angela,Kevin,Oscar" | split: "," %}
{% assign management = "David,Jan,Michael" | split: "," %}
{% assign company = '{}' | parse_json %}
{% assign company = company | add_hash_key: "name", "Dunder Mifflin" %}
{% assign company = company | add_hash_key: "accountants", accountants %}
{% assign company = company | add_hash_key: "management", management %}
{{ company }} => {"name"=>"Dunder Mifflin", "accountants"=>["Angela", "Kevin", "Oscar"], "management"=>["David", "Jan", "Michael"]}
      

add_to_array

Returns: Array<Object> - array to which you add the item given as the second parameter

Params

  • array (Array<Object>) - array to which you add a new element
  • item (Object) - item you add to the array

Examples


        {% assign array = 'a,b,c' | split: ',' %}
{{ array | add_to_array: 'd' }} => ['a', 'b', 'c', 'd']
      

add_to_date

Returns: Date - modified Date

Params

  • time (StringIntegerDateTime)
  • number (Integer) - default: 1
  • unit (String) - time unit - allowed options are: y, years, mo, months, w, weeks, d [default], days, h, hours, m, minutes, s, seconds - default: 'd'

Examples


        {{ '2010-01-01' | add_to_date: 1 }} => 2010-01-02
{{ '2010-01-01' | add_to_date: 1, 'mo' }} => 2010-02-01
      

add_to_time

Returns: Time - modified time

Params

  • time (StringIntegerDateTime)
  • number (Integer) - default: 1
  • unit (String) - time unit - allowed options are: y, years, mo, months, w, weeks, d [default], days, h, hours, m, minutes, s, seconds - default: 'd'

Examples


        {{ 'now' | add_to_time: 1, 'w' }} # => returns current time plus one week
{{ 'now' | add_to_time: 3, 'mo' }} # => returns current time plus three months
      

advanced_format

Returns: String - formatted string

Params

  • argument_to_format (Object) - object you want to format
  • format (String) - should look like: %[flags][width][.precision]type. For more examples and information see: https://ruby-doc.org/core-2.5.1/Kernel.html#method-i-sprintf

Examples


        {{ 3.124 | advanced_format: '%.2f' }} => 3.12
      

        {{ 3 | advanced_format: '%.2f' }} => 3.00
In the example above flags is not present, width is not present (refers to the total final
length of the string), precision ".2" means 2 digits after the decimal point,
type "f" means floating point
      

any

Returns: Boolean - checks if given array contains at least one of the queried string/number

Params

  • array (Array) - array to search in - default: []
  • query (StringNumber) - String/Number compared to each item in the given array - default: 'true'

Examples


        {% assign elements = 'foo,bar' | split: ',' %}
{{ elements | any: 'foo' }} => true
      

asset_url

Returns: String - URL to the physical file if existing, root asset URL otherwise

Params

  • file_path (String) - path to the asset, relative to assets directory

Examples


        {{ "valid/file.jpg" | asset_url }} => https://cdn-server.com/valid/file.jpg?updated=1565632488
{{ "nonexistent/file.jpg" | asset_url }} => https://cdn-server.com/assets/nonexistent/file.jpg
      

base64_decode

Returns: String - decoded string

Params

  • base64_string (String) - Base64 encoded string

Examples


        {{ 'aGVsbG8gYmFzZTY0\n' | base64_decode }} => 'hello base64'
      

base64_encode

Returns: String - Returns the Base64-encoded version of bin. This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.

Params

  • bin (String) - string to be encoded

Examples


        {{ 'hello base64' | base64_encode }} => 'aGVsbG8gYmFzZTY0'
      

compact

Returns: Array<Object> - array from which blank values are removed

Params

  • array (Array<Object>) - array with some blank values
  • property (String) - optionally if you provide Array<hash> as argument, you can remove elements which given key is blank</hash> - default: nil

Examples


        {{ '1,' | split: ',' | add_to_array: false | add_to_array: '2' | compact }} => 12
      

        {{ '1,' | split: ',' | add_to_array: null | add_to_array: '2' | compact }} => 12
      

        {% parse_json empty_object %}{}{% endparse_json %}
{{ '1,' | split: ',' | add_to_array: empty_object | add_to_array: '2' | compact }} => 12
      

        {% assign empty_array = ',' | split: ',' %}
{{ '1,' | split: ',' | add_to_array: empty_array | add_to_array: '2' | compact }} => 12
      

        {% parse_json hash %}[{ "hello": null }, { "hello" => "world" }, { "hello" => "" }]{% endparse_json %}
{{ hash | compact: "hello" }} => [{ "hello":  "world" }]
      

compute_hmac

Returns: String - Keyed-hash message authentication code (HMAC), that can be used to authenticate requests from third party apps, e.g. Stripe webhooks requests

Params

  • data (String) - message to be authenticated
  • secret (String) - secret key
  • algorithm (String) - defaults to SHA256. Supported algorithms are: SHA, SHA1, SHA224, SHA256, SHA384, SHA512, MD4, MDC2, MD5, RIPEMD160, DSS1. - default: 'sha256'
  • digest (String) - defaults to hex. Supported digest values are hex, none, base64 - default: 'hex'

Examples


        {{ 'some_data' | compute_hmac: 'some_secret', 'MD4' }} => 'cabff538af5f97ccc27d481942616492'
      

detect

Returns: Object - first object from the collection that matches the specified conditions

Params

  • objects (Array<Object>) - array of objects to be processed
  • conditions (Hash) - hash with conditions { field_name: value } - default: {}

Examples


        {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"}]
{{ objects | detect: foo: 2 }} => {"foo":2,"bar":"b"}
      

dig

Returns: Object - Extracted nested value specified by the sequence of keys by calling dig at each step, returning null if any intermediate step is null.

Params

  • hash (Hash)
  • keys (Array) - comma separated sequence of string keys to dig down the hash

Examples


        {% parse_json user_json %}
{
  "name": {
    "first": "John"
    "last": "Doe"
  }
}
{% endparse_json %}
{{ user_json | dig: "name", "first" }} => "John"
      

download_file

Returns: String - Body of the remote file

Params

  • url (String) - url to a remote file
  • max_size (Float) - max file size of the file, default 1 megabyte. Can't exceed 50 megabytes. - default: 1

Examples


        {{ 'http://www.example.com/my_file.txt' | download_file }} => "Content of a file"
{% assign data = 'https://example.com/data.json' | download_file | parse_json %}
      

encrypt

escape_javascript

Returns: String - escaped text

Params

  • text (String) - text to be escaped

Examples


        {% capture js %}
var msg = 'hello world';
function yell(x) {
  if (!x) { return; }
  return x + "!!!";
}
yell(msg).
{% endcapture %}

{{ js | escape_javascript }}
=> \nvar msg = \'hello world\';\nfunction yell(x) {\n if (!x) { return; }\n return x + \"!!!\";\n}\nyell(msg).\n
      

expand_url_template

Returns: String - expanded URL

Params

  • template (String) - URL template
  • params (Hash) - hash with data injected into template

Examples


        {% assign template = "/search/{city}/{street}" %}
{{ template | expand_url_template city: "Sydney", street: "BlueRoad" }}
=> /search/Sydney/BlueRoad
      

extract_url_params

Returns: Hash - hash with extracted params

Params

  • url (String) - URL with params to extract
  • templates (StringArray<String>) - URL templates array. Read more at https://tools.ietf.org/html/rfc6570

Examples


        {% assign template = "/search/{city}/{street}" %}
{{ "/search/Sydney/BlueRoad" | extract_url_params: template  }} => {"city":"Sydney","street":"BlueRoad"}
      

        {% assign template = "/{first}/{-list|\/|second}" %}
{{ "/a/b/c/" | extract_url_params: template }} => {"first":"a","second":["b", "c"]}
      

        {% assign template = "/{first}/{second}{?limit,offset}" %}
{{ "/my/path?limit=10&offset=0" | extract_url_params: template }} => {"first":"my","second":"path","limit":"10","offset":"0"}
      

        {% assign template = "/search/-list|+|query" %}
{{ "/search/this+is+my+query" | extract_url_params: template }} => {"query":["this","is","my","query"]}
      

        {% assign template = "{+location}/listings" %}
{{ "/Warsaw/Poland/listings" | extract_url_params: template }} => {"location":"/Warsaw/Poland"}
      

flatten

Returns: Array<Object> - with objects

Params

  • array (Array<Array>) - array of arrays to be processed

Examples


        {{ array_of_arrays }} => [[1,2], [3,4], [5,6]]
{{ array_of_arrays | flatten }} => [1,2,3,4,5,6]
      

format_number

Returns: String - formatted number

Params

  • number (Object) - string (numberlike), integer or float to format
  • locale () - Sets the locale to be used for formatting (defaults to current locale).
  • precision () - Sets the precision of the number (defaults to 3).
  • significant () - If true, precision will be the number of significant_digits. If false, the number of fractional digits (defaults to false).
  • separator () - Sets the separator between the fractional and integer digits (defaults to ".").
  • delimiter () - Sets the thousands delimiter (defaults to "").
  • strip_insignificant_zeros () - If true removes insignificant zeros after the decimal separator (defaults to false).

Examples


        {{ 111.2345 | format_number }} # => 111.235
      

        {{ 111.2345 | format_number: precision: 2 }} # => 111.23
      

        {{ 111 | format_number: precision: 2 }} # => 111.00
      

        {{ 1111.2345 | format_number: precision: 2, separator: ',', delimiter: '.' }} # => 1.111,23
      

group_by

Returns: Hash<MethodResult => Array<Object>> - the original array grouped by method specified by the second parameter

Params

  • objects (Array<Object>) - array to be grouped
  • method_name (String) - method name to be used to group Objects

Examples


        {% parse_json objects %}
  [
    { "size": "xl", "color": "red"},
    { "size": "xl", "color": "yellow"},
    { "size": "s", "color": "red"}
  ]
{% endparse_json %}

{{ objects | group_by: 'size' }} => {"xl"=>[{"size"=>"xl", "color"=>"red"}, {"size"=>"xl", "color"=>"yellow"}], "s"=>[{"size"=>"s", "color"=>"red"}]}
      

html_safe

Returns: String - string that can be rendered with all HTML tags, by default all variables are striped from dangerous HTML tags

Params

  • text (String)

Examples


        {{ '<h1>Hello</h1>' }} => '<h1>Hello</h1>'
{{ '<h1>Hello</h1>' | html_safe }} => '<h1>Hello</h1>'
      

        {{ '<script>alert("Hello")</script>' }} => <script>alert("Hello")</script> - this will just print text in the source code of the page
{{ '<script>alert("Hello")</script>' | html_safe }} => <script>alert("Hello")</script> - this script will be evaluated when a user enters the page
      

humanize

Returns: String - a human readable string derived from the input; capitalizes the first word, turns underscores into spaces, and strips a trailing '_id' if present. Used for creating a formatted output (e.g. by replacing underscores with spaces, capitalizing the first word, etc.).

Params

  • key (String) - input string to be transformed

Examples


        {{ 'car_model' | humanize }} => 'Car model'
      

        {{ 'customer_id' | humanize }} => 'Customer'
      

in_groups_of

Returns: Array<Array<Object>> - the original array split into groups of the size specified by the second parameter (an array of arrays)

Params

  • array (Array<Object>) - array to be split into groups
  • integer (Integer) - the size of each group the array is to be split into

Examples


        {% assign elements = '1,2,3,4' | split: ',' %}
{{ elements | in_groups_of: 3 }} => [[1, 2, 3], [4, null, null]]
      

intersection

Returns: Array<Object> - that exists in both arrays

Params

  • array (Array<Object>) - array of objects to be processed
  • other_array (Array<Object>) - array of objects to be processed

Examples


        {% assign array = '1,2,3,4' | split: ',' %}
{% assign other_array = '3,4,5,6' | split: ',' %}

{{ array | intersection: other_array }} => [3,4]
      

is_date_before(aliases: date_before)

Returns: Boolean - returns true if the first time is lower than the second time

Params

  • first_time (StringIntegerDateTime) - time to compare to the second parameter
  • second_time (StringIntegerDateTime) - time against which the first parameter is compared to

Examples


        {{ '2010-01-02' | date_before: '2010-01-03' }} => true
      

        {{ '6 months ago' | date_before: '2010-01-03' }} => false
      

        {{ '1 day ago' | date_before: 'now' }} => true
      

is_date_in_past

Returns: Boolean - true if time passed is in the past, false otherwise

Params

  • time (StringIntegerDateTime) - time object, can also be a string
  • now (StringIntegerDateTime) - sets the time from which operation should be performed

Examples


        {{ '2010-01-01' | is_date_in_past }} => true
      

        {{ '3000-01-01' | is_date_in_past }} => false
      

is_token_valid

["Temporary token is valid for desired number of hours (by default 48), which you can use to authorize the user in third party application. To do it, include it in a header with name UserTemporaryToken. Token will be invalidated on password change."]

Returns: Boolean - returns true if the token has not expired and was generated for the given user, false otherwise

Params

  • token (String) - encrypted token generated via the temporary_token GraphQL property
  • user_id (Integer) - id of the user who generated the token

Examples


        {% token = '1234' %}
{{ token | is_token_valid: context.current_user.id }} => false
      

json(aliases: to_json)

Returns: String - JSON formatted string containing a representation of object.

Params

  • object (Object) - object you want a JSON representation of

Examples


        {{ user | json }} => {"name":"Mike","email":"mike@mail.com"}
      

jwt_decode

Returns: Hash - result of decoding JWT token

Params

  • encoded_token (String) - encoded JWT token you want to decode
  • algorithm (String) - the algorithm that was used to encode the token
  • secret (String) - either a shared secret or a PUBLIC key for RSA Valid options: none - unsigned token HS256 - SHA-256 hash algorithm HS384 - SHA-384 hash algorithm HS512 - SHA-512 hash algorithm RS256 - RSA using SHA-256 hash algorithm RS384 - RSA using SHA-384 hash algorithm RS512 - RSA using SHA-512 hash algorithm - default: ''

Examples


        {% assign original_payload = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.XT8sHXyPTA9DoHzssXh1q6Uv2D1ENosW0F3Ixle85L0' | jwt_decode: 'HS256', 'this-is-secret'  }} =>
[
  {
    "key" => "value",
    "another_key" => "another value"
  },
  {
    "typ" => "JWT",
    "alg" => "HS256"
  }
]
      

        RSA:
{% capture public_key %}
-----BEGIN PUBLIC KEY-----
MIIBI...
-----END PUBLIC KEY-----
{% endcapture %}
{% assign original_payload = 'some encoded token' | jwt_decode: 'RS256', public_key %}
      

jwt_encode

Returns: String - JWT token encrypted using the algorithm of your choice

Params

  • payload (Hash) - payload or message you want to encrypt
  • algorithm (String) - algorithm you want to use for encryption
  • secret (String) - either a shared secret or a private key for RSA - default: nil
  • header_fields (Hash) - optional hash of custom headers to be added to default { "typ": "JWT", "alg": "[algorithm]" } - default: {}

Examples


        {% parse_json payload %}
{
  "key": "value",
  "another_key": "another value"
}
{% endparse_json %}

{{ payload | jwt_encode: 'HS256', 'this-is-secret' }} => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.XT8sHXyPTA9DoHzssXh1q6Uv2D1ENosW0F3Ixle85L0'
      

        {% parse_json payload %}
{
  "key": "value",
  "another_key": "another value"
}
{% endparse_json %}

{% parse_json headers %}
{
  "cty": "custom"
}
{% endparse_json %}

{{ payload | jwt_encode: 'HS256', 'this-is-secret', headers }} => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6ImN1c3RvbSJ9.eyJrZXkiOiJ2YWx1ZSIsImFub3RoZXJfa2V5IjoiYW5vdGhlciB2YWx1ZSJ9.5_-LcqcbLMeswMw04UfXqDyqAEk1x-Pwi9nwGMqxHtQ'
      

        RSA:
{% capture private_key %}
-----BEGIN RSA PRIVATE KEY-----
MIIEpA...
-----END RSA PRIVATE KEY-----
{% endcapture %}
{% assign jwt_token = payload | jwt_encode: 'RS256', private_key  %}
{% comment %} Please note that storing private key as a plain text in a code is not a good idea. We suggest you
              provide the key via Partner Portal and use context.constants.<name of private key constant> instead.{% endcomment %}
      

limit

Returns: Array<Object> - parameter; [1,2,3,4] limited to 2 elements gives [1,2]

Params

  • array (Array<Object>) - array to shrink
  • limit (Integer) - number of elements to be returned

Examples


        items => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | limit: 1 }} => [{ id: 1, name: 'foo', label: 'Foo' }]
      

localize(aliases: l)

Returns: String, nil - formatted representation of the passed parsable time

Params

  • time (StringIntegerDateTime) - parsable time object to be formatted
  • format (String) - the format to be used for formatting the time; default is 'long'; other values can be used: they are taken from translations, keys are of the form 'time.formats.#!{format_name}' - default: 'long'
  • zone (String) - the time zone to be used for time - default: nil
  • now (StringIntegerDateTime) - sets the time from which operation should be performed

Examples


        {{ '2010-01-01' | localize }} => 'January 01, 2010'
      

        {{ 'in 14 days' | localize: 'long', '', '2011-03-15' }} => 'March 14, 2011'
      

map

Returns: Array - array which includes all values for a given key

Params

  • object (Array<Hash>) - array of Hash to be processed. Nulls are skipped.
  • key (String) - name of the hash key for which all values should be returned in array of objects

Examples


        {% assign objects = '[{"id":1,"name":"foo","label":"Foo"},{"id":2,"name":"bar","label":"Bar"}]' | parse_json %}
{{ objects | map: 'name' }} => ['foo', 'bar']
      

map_attributes

Returns: Array<Array> - array of arrays with values for given keys

Params

  • array (Array<Hash>) - array of objects to be processed
  • attributes (Array<String>) - array of keys to be extracted

Examples


        items => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | map_attributes: 'id', 'name' }} => [[1, 'foo'], [2, 'bar']]
      

markdown(aliases: markdownify)

Returns: String - processed text with markdown syntax changed to HTML

Params

  • text (String) - text using markdown syntax

Examples


        {{ '**Foo**' | markdown }} => '<b>Foo</b>'
      

        {{ '# Foo' | markdown }}  => '<h1>Foo</h1>'
      

        {{ '<b>Foo</b>' | markdown }}  => '<b>Foo</b>'
      

        {{ '<div>Foo</div>' | markdown }}  => 'Foo' # If you need unsecure tags you have to use also `html_safe | sanitize` filters
      

matches

Returns: Boolean - whether the given string matches the given regular expression; returns null if

Params

  • text (String) - string to check against the regular expression
  • regexp (String) - string representing a regular expression pattern against which to match the first parameter

Examples


        {{ 'foo' | matches: '[a-z]' }} => true
      

pad_left

Returns: String - returns string padded from left to the length of count with the symbol character

Params

  • str (String) - string to pad
  • count (Integer) - minimum length of output string
  • symbol (String) - string to pad with - default: ' '

Examples


        {{ 'foo' | pad_left: 5 }} => '  foo'
      

        {{ 'Y' | pad_left: 3, 'X' }} => 'XXY'
      

parameterize

Returns: String - replaces special characters in a string so that it may be used as part of a 'pretty' URL; the default separator used is '-';

Params

  • text (String) - input string to be 'parameterized'
  • separator (String) - string to be used as separator in the output string; default is '-' - default: '-'

Examples


        {{ 'John arrived_foo' | parameterize }} => 'john-arrived_foo'
      

parse_json(aliases: to_hash)

Returns: Hash - Hash created based on JSON

Params

  • object (Object) - String containing valid JSON

Examples


        {% assign text = '{ "name": "foo", "bar": {} }' %}
{% assign object = text | parse_json %}
{{ object.name }} => 'foo'
      

pluralize

Returns: String - pluralized version of the input string

Params

  • string (String) - string to be pluralized
  • count (Number) - optional count number based on which string will be pluralized or singularized - default: 2

Examples


        {{ 'dog' | pluralize: 1 }} => 'dog'
{{ 'dog' | pluralize: 2 }} => 'dogs'
      

pricify

Returns: String - formatted price using global price formatting rules

Params

  • amount (NumericString) - amount to be formatted
  • currency (String) - currency to be used for formatting - default: 'USD'

Examples


        {{ 0 | pricify }} => $0
      

        {{ 1 | pricify }} => $1
      

        {{ 1.20 | pricify }} => $1.20
      

        {{ 1000000 | pricify }} => $1,000,000
      

        {{ 1 | pricify: "PLN" }} => 1 zł
      

        {{ 1 | pricify: "JPY" }} => ¥1
      

pricify_cents

Returns: String - formatted price using the global price formatting rules

Params

  • amount (NumericString) - amount in cents to be formatted
  • currency (String) - currency to be used for formatting - default: 'USD'

Examples


        {{ 1 | pricify_cents }} => $0.01
      

        {{ 100 | pricify_cents }} => $1
      

        {{ 1000000 | pricify_cents }} => $10,000
      

        {{ 1 | pricify_cents: "PLN" }} => 0.01 zł
      

        {{ 1 | pricify_cents: "JPY" }} => ¥1
      

querify

Returns: String - a query string

Params

  • hash (Hash{Object => Object}) - hash to be "querified"

Examples


        {{ hash }} => { 'name' => 'Dan', 'id' => 1 }
{{ hash | querify }} => 'name=Dan&id=1'
      

random_string

Returns: String - returns a random alphanumeric string of given length

Params

  • length (Int) - how many random characters should be included; default is 12 - default: 12

Examples


        {{ 10 | random_string }} => '6a1ee2629'
      

raw_escape_string

Returns: String - HTML-escaped input string; returns a string with its HTML tags visible in the browser

Params

  • value (String) - input string to be HTML-escaped

Examples


        {{ 'foo<b>bar</b>' | raw_escape_string }} => 'foo&lt;b&gt;bar&lt;/b&gt;'
      

regex_matches

Returns: Array<Array<String>> - matches for the expression in the string; each item in the array is an array containing all groups of matches; for example for the regex (.)(.) and the text 'abcdef', the result will look like: [["a", "b"], ["c", "d"], ["e", "f"]]

Params

  • text (String)
  • regexp (String) - regexp to use for matching
  • options (String) - can contain 'ixm'; i - ignore case, x - extended, m # - multiline (e.g. 'ix', 'm', 'mi' etc.) - default: ''

Examples


        To retrieve the URL from a meta tag see the example below:
{% assign text = '<html><head><meta property="og:image" content="http://somehost.com/someimage.jpg" /></head><body>content</body></html>' | html_safe %}

{% assign matches = text | regex_matches: '<meta\s+property="og:image"\s+content="([^"]+)"' %}

{% if matches.size > 0 %}
  {% assign image_path = matches[0][0] %}
  {{ image_path }}
{% endif %}
      

reject

Returns: Array<Object> - with objects from collection that don't match provided conditions

Params

  • objects (Array<Object>) - array of objects to be processed
  • conditions (Hash) - hash with conditions { field_name: value } - default: {}

Examples


        {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | reject: foo: 2 }} => [{"foo":1,"bar":"a"},{"foo":3,"bar":"c"}]
      

remove_hash_key(aliases: delete_hash_key)

Returns: Object - value which was assigned to a deleted key. If the key did not exist in the first place, null is returned.

Params

  • hash (Hash)
  • key (String)

Examples


        {% assign hash = '{ "a": "1", "b": "2"}' | parse_json %}
{% assign a_value = hash | remove_hash_key: "a" %}
{{ a_value }} => "1"
{{ hash }} => { "b": "2" }
      

replace_regex

Returns: String - string with regexp pattern replaced by replacement text

Params

  • text (String)
  • regexp (String) - regexp to use for matching
  • replacement (String) - replacement text, or hash; if hash, keys in the hash must be matched texts and values their replacements
  • options (String) - can contain 'ixm'; i - ignore case, x - extended, m # - multiline (e.g. 'ix', 'm', 'mi' etc.) - default: ''
  • global (Boolean) - whether all occurrences should be replaced or just the first - default: true

Examples


        Basic example:
{{ "fooooo fooo" | replace_regex: 'o+', 'o' }} => "fo fo"
      

        Global set to false:
{{ "fooooo fooo" | replace_regex: 'o+', 'o', '', false }} => "fo fooo"
      

        Hash replacement:
{% assign hash = '{}' | parse_json %}
{% assign hash = hash | add_hash_key: 'ooooo', 'bbbbb' %}
{% assign hash = hash | add_hash_key: 'ooo', 'ccc' %}
{{ "fooooo fooo" | replace_regex: 'o+', hash }} => "fbbbbb fccc"
      

        Using options, ignore case:
{{ "FOOOOO" | replace_regex: 'o+', 'a', 'i' }} => "Fa"
{{ "FOOOOO" | replace_regex: 'o+', 'a' }} => "FOOOOO"
Using options, extended mode (insert spaces, newlines, and comments in the pattern to make it more readable):
{{ "FOOOOO" | replace_regex: 'o+ #comment', 'a', 'ix' }} => "Fa"
Using options, multiline (. matches newline):
{% capture newLine %}
{% endcapture %}
{{ "abc" | append: newLine | append: "def" | append: newLine | append: "ghi" | replace_regex: '.+', 'a', 'im' }} => "a"
      

rotate

Returns: Array<Object> - the input array rotated by a number of times given as the second parameter; [1,2,3,4] rotated by 2 gives [3,4,1,2]

Params

  • array (Array<Object>) - array to be rotated
  • count (Integer) - number of times to rotate the input array - default: 1

Examples


        {% assign numbers = "1,2,3" | split: "," %}
{{ numbers | rotate }} => [2,3,1]
      

sanitize

Returns: String

Params

  • input (String)
  • whitelist_attributes (Array<String>) - default: nil
  • whitelist_tags (Array<String>) - default: nil

Examples


        {% capture link %}
  <a href="javascript:prompt(1)" target="_blank">Link</a>
{% endcapture %}
{{ link | sanitize }} => <a href="">Link</a>
{% assign whitelist_attributes = 'target' | split: '|' %}
{{ link | sanitize: whitelist_attributes }} => <a href="" target="_blank">Link</a>
      

select

Returns: Array<Object> - with objects from collection that matches provided conditions

Params

  • objects (Array<Object>) - array of objects to be processed
  • conditions (Hash) - hash with conditions { field_name: value } - default: {}

Examples


        {{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | select: foo: 2 }} => [{"foo":2,"bar":"b"},{"foo":2,"bar":"d"}]
      

sha1

Returns: String - SHA1 digest of the input object

Params

  • object (String) - input object that you want to obtain the digest for

Examples


        {{ 'foo' | sha1 }} => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
      

shuffle_array

Returns: Array<Array> - array with shuffled items

Params

  • array (Array<Object>) - array of objects to be processed

Examples


        items => [1, 2, 3, 4]
{{ items | shuffle_array }} => [3, 2, 4, 1]
      

slugify

Returns: String - replaces special characters in a string so that it may be used as part of a 'pretty' URL;

Params

  • text (String) - input string to be 'slugified'

Examples


        {{ 'John arrived_foo' | slugify }} => 'john-arrived-foo'
      

strftime

Returns: String - formatted representation of the time object; the formatted representation will be based on what the format parameter specifies

Params

  • time (StringIntegerDateTimeDateTime) - parsable time object
  • format (String) - string representing the desired output format e.g. '%Y-%m-%d' will result in '2020-12-21' Cheatsheet: https://devhints.io/strftime
  • zone (String) - string representing the time zone - default: nil
  • now (StringIntegerDateTime) - sets the time from which operation should be performed - default: nil

Examples


        {{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M' }} => 2018-05-30 09:12
      

        {% assign time = '2010-01-01 08:00' | to_time %}
{{ time | strftime: "%Y-%m-%d" }} => '2010-01-01'
      

        {{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Europe/Warsaw' }} => 2018-05-30 18:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'America/New_York' }} => 2018-05-30 12:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Sydney' }} => 2018-05-31 02:12
{{ '2018-05-30T09:12:34.000-07:00' | strftime: '%Y-%m-%d %H:%M', 'Pacific/Apia' }} => 2018-05-31 05:12
      

subtract_array

Returns: Array<Object> - that is a difference between two arrays

Params

  • array (Array<Object>) - array of objects to be processed
  • other_array (Array<Object>) - array of objects to be processed

Examples


        {% assign array = '1,2' | split: ',' %}
{% assign other_array = '2' | split: ',' %}

{{ array | subtract_array: other_array }} => [1]
      

sum_array

Returns: Numeric - summarised value of array

Params

  • array (Array<Numeric>) - array with values to be summarised

Examples


        {% assign numbers = '[1,2,3]' | parse_json %}
{{ numbers | sum_array }} => 6
      

time_diff

Returns: Float - duration between start and finish in unit; default is ms (milliseconds)

Params

  • start (StringIntegerDateTime)
  • finish (StringIntegerDateTime)
  • unit (String) - time unit - allowed options are: d, days, h, hours, m, minutes, s, seconds, ms, milliseconds [default] - default: 'ms'
  • precision (Integer) - defines rounding after comma; default is 3 - default: 3

Examples


        {% assign result = 'now' | time_diff: 'in 5 minutes', 'd' %}
{% log result %}
      

titleize

Returns: String - capitalizes all the words and replaces some characters in the string to create a string in title-case format

Params

  • text (String) - string to be processed

Examples


        {{ 'foo bar_zoo-xx' | titleize }} => 'Foo Bar Zoo Xx'
      

to_date

Returns: Date - a Date object obtained/parsed from the input object

Params

  • time (StringIntegerDateTime) - parsable time object to be converted to date
  • now (StringIntegerDateTime) - sets the time from which operation should be performed

Examples


        {{ '2010-01-01 8:00:00' | to_date }} => 2010-01-01
      

to_mobile_number

Returns: String - returns mobile number in E.164 format; recommended for sending sms notifications

Params

  • number (String) - the base part of mobile number
  • country (String) - country for which country code should be used. Can be anything - full name, iso2, iso3 - default: nil

Examples


        {{ '500 123 999' | to_mobile_number: 'PL' }} => '+48500123999'
      

to_positive_integer

Returns: Integer

Params

  • param (Object) - value to be coerced to positive integer
  • default (Integer) - default value in case param is not valid positive integer

Examples


        {{ '1' | to_positive_integer: 2 }} => 1
{{ '' | to_positive_integer: 2 }} => 2
      

to_time

Returns: DateTime - a time object created from parsing the string representation of time given as input

Params

  • time (StringIntegerDateTime) - a string representation of time ('today', '3 days ago', 'in 10 minutes' etc.) or an integer in UNIX time format or time
  • zone (String) - time zone - default: nil
  • format (String) - specific format to be used when parsing time - default: nil
  • now (StringIntegerDateTime) - sets the time from which operation should be performed - default: nil

Examples


        {{ 'today' | to_time }} => 2017-04-15 15:21:00
      

        {{ 'today' | to_time: 'UTC' }} => 2017-04-15 15:21:00
      

        {{ '1 day ago' | to_time }} => 2017-04-14 15:21:00
      

        {{ '5 days from now' | to_time }} => 2017-04-19 15:21:00
      

        {{ '2010:01:01' | to_time: '', '%Y:%m:%d' }} => 2010-01-01 00:00:00
      

        {{ '5 days from now' | to_time '', '', '2019-10-01' }} => 2019-10-06 00:00:00 # equivalent of {{ '2019-10-01' | add_to_time: 5, 'days' }}
      

translate(aliases: t)

Returns: String - translation value taken from translations YML file for the key given as parameter

Params

  • key (String) - translation key
  • options (Hash{String => String}) - values passed to translation string - default: {}

Examples


        {{ 'beer' | translate }} => 'cerveza'
      

        {{ 'beer' | t }} => 'cerveza'
      

        {{ 'drinks.alcoholic.beer' | t }} => 'piwo'
      

useragent

Returns: Hash - parsed browser user agent information

Params

  • useragent_header (String) - browser user agent from the request header

Examples


        {{ context.headers.HTTP_USER_AGENT | useragent }} =>
{
  "device": {"family":"Other","model":"Other","brand":null},
  "family":"Firefox",
  "os":{"version":null,"family":"Windows 7"},
  "version":{"version":"47.0","major":"47","minor":"0","patch":null}
}
      

uuid

Returns: String - Universally unique identifier v4

Params

  • _dummy (String) - parameter will be ignored - default: nil

Examples


        {{ '' | uuid }} => "2d931510-d99f-494a-8c67-87feb05e1594"

{% assign id = '' | uuid %}
{{ id }} => "b12bd15e-4da7-41a7-b673-272221049c01"
      

verify_access_key

Returns: Boolean

Params

  • access_key (String) - can be obtained in Partner Portal

Examples


        {% assign access_key = '12345' %}
{{ access_key | verify_access_key }} => true
      

video_params

Returns: Hash - metadata about video

Params

  • url (String) - URL to a video on the internet

Examples


        {{ 'https://www.youtube.com/watch?v=8N_tupPBtWQ' | video_params }}
=> {"provider"=>"YouTube", "url"=>"https://www.youtube.com/watch?v=8N_tupPBtWQ", "video_id"=>"8N_tupPBtWQ", "embed_url"=>"https://www.youtube.com/embed/8N_tupPBtWQ", "embed_code"=>"<iframe src=\"https://www.youtube.com/embed/8N_tupPBtWQ\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\"></iframe>"},
      

videoify

Returns: String - if the given URL is supported, an HTML formatted string containing a video player (inside an iframe) which will play the video at the given URL; otherwise an empty string is returned

Params

  • url (String) - URL to a video on the internet - default: ''

asset_path

Returns: String - relative path to the physical file decorated with updated param to invalidate CDN cache. Always prefer asset_url,

Params

  • file_path (String) - path to the asset, relative to assets directory

Examples


        {{ "valid/file.jpg" | asset_path }} => /assets/valid/file.jpg?updated=1565632488
{{ "nonexistent/file.jpg" | asset_path }} => /assets/nonexistent/file.jpg
      

fetch

Returns: Object

Params

  • hash (Hash) - input hash to be traversed
  • key (String) - key to be fetched from hash branch

Examples


        {% parse_json users %}
[{
  "name": "Jane"
}, {
  "name": "Bob"
}]
{% endparse_json %}
{{ users | first | fetch: "name" }} => "Jane"
      

is_included_in_array

Returns: Boolean - whether the array includes the element given

Params

  • array (Array) - array of elements to look into
  • el (Object) - look for this element inside the array

Examples


        {% assign elements = 'a,b,c,d' | split: ',' %}
{{ elements | is_included_in_array: 'c' }} => true
      

new_line_to_br(aliases: nl2br)

Questions?

We are always happy to help with any questions you may have.

contact us