Liquid - platformOS Liquid Filters
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_to_time
Params
- time (StringIntegerDateTime)
- number (Number) - 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'
Returns
Time - modified time
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
Params
- argument_to_format (Untyped) - 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
Returns
String - formatted string
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
amount_to_fractional
Converts amount in given currency to fractional. For example, convert USD to cents.
Params
- amount (NumericString) - amount to be changed to fractional
- currency (String) - currency to be used - default: 'USD'
Returns
Number - Amount in fractional, for example cents for USD
Examples
{{ 10.50 | amount_to_fractional: 'USD' }} => 1050
{{ 10.50 | amount_to_fractional: 'JPY' }} => 11
array_add (aliases: add_to_array)
Params
- array (Array) - array to which you add a new element
- item (Untyped) - item you add to the array
Returns
Array - array to which you add the item given as the second parameter
Examples
{% assign array = 'a,b,c' | split: ',' %}
{{ array | array_add: 'd' }} => ['a', 'b', 'c', 'd']
array_any (aliases: any)
Params
- array (Array) - array to search in - default: []
- query (StringNumber) - String/Number compared to each item in the given array - default: 'true'
Returns
Boolean - checks if given array contains at least one of the queried string/number
Examples
{% assign elements = 'foo,bar' | split: ',' %}
{{ elements | array_any: 'foo' }} => true
array_compact (aliases: compact)
Removes blank elements from the array
Params
- array (ArrayHash) - array with some blank values
- property (String) - optionally if you provide Hash as argument, you can remove elements which given key is blank - default: nil
Returns
Array - array from which blank values are removed
Examples
{{ '1,' | split: ',' | array_add: false | array_add: '2' | array_compact }} => 12
{{ '1,' | split: ',' | array_add: null | array_add: '2' | array_compact }} => 12
{% parse_json empty_object %}{}{% endparse_json %}
{{ '1,' | split: ',' | array_add: empty_object | array_add: '2' | array_compact }} => 12
{% assign empty_array = ',' | split: ',' %}
{{ '1,' | split: ',' | array_add: empty_array | array_add: '2' | array_compact }} => 12
{% parse_json hash %}[{ "hello": null }, { "hello" => "world" }, { "hello" => "" }]{% endparse_json %}
{{ hash | array_compact: "hello" }} => [{ "hello": "world" }]
array_delete
Params
- array (Array) - array to process
- element (Untyped) - value to remove
Returns
Array - the initial array that has all occurences of "element" removed
Examples
assign test = ['test', 'test2', 'test', 'test3']
assign arr = test | array_delete: 'test'
=> ['test2', 'test3']
array_delete_at
Params
- array (Array) - array to process
- index (Number) - array index to remove
Returns
Array - the initial array that has the element at index removed
Examples
assign test = ['test', 'test2']
assign arr = test | array_delete_at: 1
=> ['test']
array_detect (aliases: detect)
Params
- objects (Array) - array of objects to be processed
- conditions (Hash) - hash with conditions { field_name: value } - default: {}
Returns
Untyped - first object from the collection that matches the specified conditions
Examples
{{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"}]
{{ objects | array_detect: foo: 2 }} => {"foo":2,"bar":"b"}
array_find_index
Params
- objects (Array) - array of objects to be processed
- conditions (Hash) - hash with conditions { field_name: value }
Returns
Array - with indices from collection that matches provided conditions
Examples
{{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_find_index: foo: 2 }} => [1, 3]
array_flatten (aliases: flatten)
Params
- array (Array) - array of arrays to be processed
Returns
Array - with objects
Examples
{{ array_of_arrays }} => [[1,2], [3,4], [5,6]]
{{ array_of_arrays | array_flatten }} => [1,2,3,4,5,6]
array_group_by (aliases: group_by)
Transforms array into hash, with keys equal to the values of object's method name and value being array containing objects
Params
- objects (Array) - array to be grouped
- method_name (String) - method name to be used to group Objects
Returns
Hash - the original array grouped by method specified by the second parameter
Examples
{% parse_json objects %}
[
{ "size": "xl", "color": "red"},
{ "size": "xl", "color": "yellow"},
{ "size": "s", "color": "red"}
]
{% endparse_json %}
{{ objects | array_group_by: 'size' }} => {"xl"=>[{"size"=>"xl", "color"=>"red"}, {"size"=>"xl", "color"=>"yellow"}], "s"=>[{"size"=>"s", "color"=>"red"}]}
array_in_groups_of (aliases: in_groups_of)
Transforms array in array of arrays, each subarray containing exactly N elements
Params
- array (Array) - array to be split into groups
- number_of_elements (Number) - the size of each group the array is to be split into
Returns
Array - the original array split into groups of the size specified by the second parameter (an array of arrays)
Examples
{% assign elements = '1,2,3,4' | split: ',' %}
{{ elements | array_in_groups_of: 3 }} => [[1, 2, 3], [4, null, null]]
array_index_of
Finds index of an object in the array
Params
- array (Array) - array of objects to be processed
- object (Untyped) - object to search for
Returns
- Integer position of object in array if found or nil otherwise
Examples
{{ objects }} => [1,'abc',3]
{{ objects | array_index_of: 'abc' }} => 1
array_intersect (aliases: intersection)
Params
- array (Array) - array of objects to be processed
- other_array (Array) - array of objects to be processed
Returns
Array - that exists in both arrays
Examples
{% liquid
assign array = '1,2,3,4' | split: ','
assign other_array = '3,4,5,6' | split: ','
%}
{{ array | array_intersect: other_array }} => [3,4]
array_limit (aliases: limit)
Params
- array (Array) - array to shrink
- limit (Number) - number of elements to be returned
Returns
Array - parameter; [1,2,3,4] limited to 2 elements gives [1,2]
Examples
items => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_limit: 1 }} => [{ id: 1, name: 'foo', label: 'Foo' }]
array_map (aliases: map_attributes)
Params
- array (Array) - array of objects to be processed
- attributes (Array) - array of keys to be extracted
Returns
Array - array of arrays with values for given keys
Examples
{{ items }} => [{ id: 1, name: 'foo', label: 'Foo' }, { id: 2, name: 'bar', label: 'Bar' }]
{{ items | array_map: 'id', 'name' }} => [[1, 'foo'], [2, 'bar']]
array_prepend (aliases: prepend_to_array)
Params
- array (Array) - array to which you prepend a new element
- item (Untyped) - item you prepend to the array
Returns
Array - array to which you prepend the item given as the second parameter
Examples
{% assign array = 'a,b,c' | split: ',' %}
{{ array | array_prepend: 'd' }} => ['d', 'a', 'b', 'c']
array_reject (aliases: reject)
Params
- objects (Array) - array of objects to be processed
- conditions (Hash) - hash with conditions { field_name: value } - default: {}
Returns
Array - with objects from collection that don't match provided conditions
Examples
{{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_reject: foo: 2 }} => [{"foo":1,"bar":"a"},{"foo":3,"bar":"c"}]
array_rotate (aliases: rotate)
Params
- array (Array) - array to be rotated
- count (Number) - number of times to rotate the input array - default: 1
Returns
Array - 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]
Examples
{% assign numbers = "1,2,3" | split: "," %}
{{ numbers | array_rotate }} => [2,3,1]
array_select (aliases: select)
Params
- objects (Array) - array of objects to be processed
- conditions (Hash) - hash with conditions { field_name: value } - default: {}
Returns
Array - with objects from collection that matches provided conditions
Examples
{{ objects }} => [{"foo":1,"bar":"a"},{"foo":2,"bar":"b"},{"foo":3,"bar":"c"},{"foo":2,"bar":"d"}]
{{ objects | array_select: foo: 2 }} => [{"foo":2,"bar":"b"},{"foo":2,"bar":"d"}]
array_shuffle (aliases: shuffle_array)
Params
- array (Array) - array of objects to be processed
Returns
Array - array with shuffled items
Examples
{{ items }} => [1, 2, 3, 4]
{{ items | array_shuffle }} => [3, 2, 4, 1]
array_sort_by (aliases: sort_by)
Params
- input (Array) - Array of Hash to be sorted by a key
- property (Untyped) - property by which to sort an Array of Hashes
Returns
Array - Sorted object (Array of Hash)
Examples
array1 is [{"title": "Tester", "value": 1}, {"title": "And", "value": 2}]
{{ array1 | array_sort_by: "title" }}
array_subtract (aliases: subtract_array)
Params
- array (Array) - array of objects to be processed
- other_array (Array) - array of objects to be processed
Returns
Array - that is a difference between two arrays
Examples
{% liquid
assign array = '1,2' | split: ','
assign other_array = '2' | split: ','
%}
{{ array | array_subtract: other_array }} => [1]
array_sum (aliases: sum_array)
Params
- array (Array) - array with values to be summarised
Returns
Number - summarised value of array
Examples
{% assign numbers = '[1,2,3]' | parse_json %}
{{ numbers | array_sum }} => 6
array_uniq
Removes duplicate elements from an array
Params
- input (Array) - array to be processed
- property () - String property to be used as the comparison key {% assign result = "[[1,2],[1,2],[3,4]]" | array_uniq %} {{ result }} => "[[1,2],[3,4]]" - default: nil
Returns
Array - Returns an array with duplicate elements removed
asset_url
Generates CDN url to an asset
Params
- file_path (String) - path to the asset, relative to assets directory
Returns
String - URL to the physical file if existing, root asset URL otherwise
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
Params
- base64_string (String) - Base64 encoded string
Returns
String - decoded string
Examples
{{ 'aGVsbG8gYmFzZTY0\n' | base64_decode }} => 'hello base64'
base64_encode
Params
- bin (String) - string to be encoded
Returns
String - Returns the Base64-encoded version of bin. This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.
Examples
{{ 'hello base64' | base64_encode }} => 'aGVsbG8gYmFzZTY0'
compute_hmac
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'
Returns
String - Keyed-hash message authentication code (HMAC), that can be used to authenticate requests from third party apps, e.g. Stripe webhooks requests
Examples
{{ 'some_data' | compute_hmac: 'some_secret', 'MD4' }} => 'cabff538af5f97ccc27d481942616492'
date_add (aliases: add_to_date)
Params
- time (StringIntegerDateTime)
- number (Number) - 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'
Returns
Date - modified Date
Examples
{{ '2010-01-01' | date_add: 1 }} => 2010-01-02
{{ '2010-01-01' | date_add: 1, 'mo' }} => 2010-02-01
decrypt
Filter allowing to decrypt data encrypted with a specified algorithm. See encrypt filter for encryption.
Params
- payload (String) - string payload to be decrypted - must be a Base64 encoded (RFC 4648) or HEX (if from_hex flag true) string
-
algorithm
(String)
- algorithm you want to use for encryption
- symmetric (String) - Supported algorithms: aes-128-cbc, aes-128-cbc-hmac-sha1, aes-128-cbc-hmac-sha256, aes-128-ccm, aes-128-cfb, aes-128-cfb1, aes-128-cfb8, aes-128-ctr, aes-128-ecb, aes-128-gcm, aes-128-ocb, aes-128-ofb, aes-128-xts, aes-192-cbc, aes-192-ccm, aes-192-cfb, aes-192-cfb1, aes-192-cfb8, aes-192-ctr, aes-192-ecb, aes-192-gcm, aes-192-ocb, aes-192-ofb, aes-256-cbc, aes-256-cbc-hmac-sha1, aes-256-cbc-hmac-sha256, aes-256-ccm, aes-256-cfb, aes-256-cfb1, aes-256-cfb8, aes-256-ctr, aes-256-ecb, aes-256-gcm, aes-256-ocb, aes-256-ofb, aes-256-xts, aes128, aes128-wrap, aes192, aes192-wrap, aes256, aes256-wrap, aria-128-cbc, aria-128-ccm, aria-128-cfb, aria-128-cfb1, aria-128-cfb8, aria-128-ctr, aria-128-ecb, aria-128-gcm, aria-128-ofb, aria-192-cbc, aria-192-ccm, aria-192-cfb, aria-192-cfb1, aria-192-cfb8, aria-192-ctr, aria-192-ecb, aria-192-gcm, aria-192-ofb, aria-256-cbc, aria-256-ccm, aria-256-cfb, aria-256-cfb1, aria-256-cfb8, aria-256-ctr, aria-256-ecb, aria-256-gcm, aria-256-ofb, aria128, aria192, aria256, bf, bf-cbc, bf-cfb, bf-ecb, bf-ofb, blowfish, camellia-128-cbc, camellia-128-cfb, camellia-128-cfb1, camellia-128-cfb8, camellia-128-ctr, camellia-128-ecb, camellia-128-ofb, camellia-192-cbc, camellia-192-cfb, camellia-192-cfb1, camellia-192-cfb8, camellia-192-ctr, camellia-192-ecb, camellia-192-ofb, camellia-256-cbc, camellia-256-cfb, camellia-256-cfb1, camellia-256-cfb8, camellia-256-ctr, camellia-256-ecb, camellia-256-ofb, camellia128, camellia192, camellia256, cast, cast-cbc, cast5-cbc, cast5-cfb, cast5-ecb, cast5-ofb, chacha20, chacha20-poly1305, des, des-cbc, des-cfb, des-cfb1, des-cfb8, des-ecb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ecb, des-ede-ofb, des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-cfb1, des-ede3-cfb8, des-ede3-ecb, des-ede3-ofb, des-ofb, des3, des3-wrap, desx, desx-cbc, id-aes128-CCM, id-aes128-GCM, id-aes128-wrap, id-aes128-wrap-pad, id-aes192-CCM, id-aes192-GCM, id-aes192-wrap, id-aes192-wrap-pad, id-aes256-CCM, id-aes256-GCM, id-aes256-wrap, id-aes256-wrap-pad, id-smime-alg-CMS3DESwrap, idea, idea-cbc, idea-cfb, idea-ecb, idea-ofb, rc2, rc2-128, rc2-40, rc2-40-cbc, rc2-64, rc2-64-cbc, rc2-cbc, rc2-cfb, rc2-ecb, rc2-ofb, rc4, rc4-40, rc4-hmac-md5, seed, seed-cbc, seed-cfb, seed-ecb, seed-ofb, sm4, sm4-cbc, sm4-cfb, sm4-ctr, sm4-ecb, sm4-ofb
- asymmetric (String) - Supported algorithms: RSA, RSA-OAEP
- key (String) - a key used for encryption. Key must match the algorithm requirments. For asymmetric algorithms there are public and private keys that need to passed in PEM format.
-
options
()
- - a Hash with additional options to control the decryption algorithm
- transform_key_to_hex (Boolean) - - transfrom key to HEX
- from_hex (Boolean) - - return HEX enxrypted string instead of Base64 encoded
- disable_cipher_padding (Boolean) - - disable cipher padding
Returns
String - String - decrypted string using the algorithm of your choice. Initialization Vector (iv) is expected to be present in the encrypted payload at the beginning.
Examples
{{ some_payload | decrypt: 'aes-256-cbc', 'ThisPasswordIsReallyHardToGuessA' }} => decrypted string from payload
{{ "43553EEDD9BFE36D10F99E931245CF8826903C00D235DFD300B3CC40BD263A621FC2FB9F5C3743F75D399A912AFABF92371927C6D190E0EFF19EAE9802320391FED79D92009796403EC6B426E901AB981CE53A43557C295F3D6FC9678EE0557F" | decrypt: 'aes-128-ecb', '4FCD5FAE2AC493C0F8CE8E1E6105D194', true, true, true }} => iframe=true;customer.firstName=John;customer.lastName=Smith;header.accountNumber=6759370;header.authToken1=12345;header.paymentTypeCode=UTILITY;header.amount=123.45
deep_clone
Params
- object (Untyped) - object to be duplicated
Returns
Untyped - returns a copy of the object parameter
Examples
{% assign some_hash_copy = some_hash | deep_clone %}
digest
Params
- object (String) - message that you want to obtain a cryptographic hash for
- algorithm (String) - the hash algorithm to use. Choose from: 'md5', 'sha1', 'sha256', 'sha384', 'sha512'. Default is sha1. - default: 'sha1'
- digest (String) - defaults to hex. Supported digest values are hex, none, base64 - default: 'hex'
Returns
String - hexadecimal hash value obtained by applying the selected algorithm to the message
Examples
{{ 'foo' | digest }} => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'
{{ 'foo' | digest: 'sha256' }} => '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae'
{{ 'foo' | digest: 'sha256', 'base64' }} => 'LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564='
{{ 'foo' | digest: 'sha256', 'none' }} => ',&\xB4kh\xFF\xC6\x8F\xF9\x9BE<\x1D0A4\x13B-pd\x83\xBF\xA0\xF9\x8A^\x88bf\xE7\xAE'
download_file
Params
- url (String) - url to a remote file
- max_size (Number) - max file size of the file, default 1 megabyte. Can't exceed 50 megabytes. - default: 1
Returns
String - Body of the remote file
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 %}
encode
The filter returns a string with the encoding changed to the one specified by the 'destination_encoding' parameter. The filter changes the string itself (its representation in memory) by first determining which graphical characters the underlying bytes in the string represent in the 'source_encoding', and then changing the bytes to encode the same graphical characters in 'destination_encoding'.
Params
- text (String) - input string that we want to reencode
- source_encoding (String) - the encoding of the source string text
- destination_encoding (String) - the encoding we want the source string text converted to
- invalid (String) - if set to 'replace', invalid byte sequences for the source_encoding will be replaced with the replace parameter
- undefined (String) - if set to 'replace', characters which do not exist in the destination encoding will be replaced by the 'replace' parameter
- replace (String) - used together with the invalid and undefined parameters
Returns
String - input string with encoding modified from source_encoding to destination_encoding
Examples
{{ 'John arrived_foo' | encode: "ISO-8859-1", 'UTF-8', invalid: 'replace', undefined: 'replace', replace: '??' }}
encoding
The filter returns the encoding of the string parameter (i.e. how the underlying bytes in the string are interpreted to determine which graphical characters they encode).
Params
- text (String) - input string whose encoding we want to find
Returns
String - encoding of the string text
Examples
{{ 'John arrived_foo' | encoding }} => 'UTF-8'
encrypt
Filter allowing to encrypt data with specified algorithm. See decrypt filter for decryption
Params
- payload (String) - string payload to be encrypted
-
algorithm
(String)
- algorithm you want to use for encryption
- symmetric (String) - Supported algorithms: aes-128-cbc, aes-128-cbc-hmac-sha1, aes-128-cbc-hmac-sha256, aes-128-ccm, aes-128-cfb, aes-128-cfb1, aes-128-cfb8, aes-128-ctr, aes-128-ecb, aes-128-gcm, aes-128-ocb, aes-128-ofb, aes-128-xts, aes-192-cbc, aes-192-ccm, aes-192-cfb, aes-192-cfb1, aes-192-cfb8, aes-192-ctr, aes-192-ecb, aes-192-gcm, aes-192-ocb, aes-192-ofb, aes-256-cbc, aes-256-cbc-hmac-sha1, aes-256-cbc-hmac-sha256, aes-256-ccm, aes-256-cfb, aes-256-cfb1, aes-256-cfb8, aes-256-ctr, aes-256-ecb, aes-256-gcm, aes-256-ocb, aes-256-ofb, aes-256-xts, aes128, aes128-wrap, aes192, aes192-wrap, aes256, aes256-wrap, aria-128-cbc, aria-128-ccm, aria-128-cfb, aria-128-cfb1, aria-128-cfb8, aria-128-ctr, aria-128-ecb, aria-128-gcm, aria-128-ofb, aria-192-cbc, aria-192-ccm, aria-192-cfb, aria-192-cfb1, aria-192-cfb8, aria-192-ctr, aria-192-ecb, aria-192-gcm, aria-192-ofb, aria-256-cbc, aria-256-ccm, aria-256-cfb, aria-256-cfb1, aria-256-cfb8, aria-256-ctr, aria-256-ecb, aria-256-gcm, aria-256-ofb, aria128, aria192, aria256, bf, bf-cbc, bf-cfb, bf-ecb, bf-ofb, blowfish, camellia-128-cbc, camellia-128-cfb, camellia-128-cfb1, camellia-128-cfb8, camellia-128-ctr, camellia-128-ecb, camellia-128-ofb, camellia-192-cbc, camellia-192-cfb, camellia-192-cfb1, camellia-192-cfb8, camellia-192-ctr, camellia-192-ecb, camellia-192-ofb, camellia-256-cbc, camellia-256-cfb, camellia-256-cfb1, camellia-256-cfb8, camellia-256-ctr, camellia-256-ecb, camellia-256-ofb, camellia128, camellia192, camellia256, cast, cast-cbc, cast5-cbc, cast5-cfb, cast5-ecb, cast5-ofb, chacha20, chacha20-poly1305, des, des-cbc, des-cfb, des-cfb1, des-cfb8, des-ecb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ecb, des-ede-ofb, des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-cfb1, des-ede3-cfb8, des-ede3-ecb, des-ede3-ofb, des-ofb, des3, des3-wrap, desx, desx-cbc, id-aes128-CCM, id-aes128-GCM, id-aes128-wrap, id-aes128-wrap-pad, id-aes192-CCM, id-aes192-GCM, id-aes192-wrap, id-aes192-wrap-pad, id-aes256-CCM, id-aes256-GCM, id-aes256-wrap, id-aes256-wrap-pad, id-smime-alg-CMS3DESwrap, idea, idea-cbc, idea-cfb, idea-ecb, idea-ofb, rc2, rc2-128, rc2-40, rc2-40-cbc, rc2-64, rc2-64-cbc, rc2-cbc, rc2-cfb, rc2-ecb, rc2-ofb, rc4, rc4-40, rc4-hmac-md5, seed, seed-cbc, seed-cfb, seed-ecb, seed-ofb, sm4, sm4-cbc, sm4-cfb, sm4-ctr, sm4-ecb, sm4-ofb
- asymmetric (String) - Supported algorithms: RSA, RSA-OAEP
- key (String) - a key used for encryption. Key must match the algorithm requirments. For asymmetric algorithms there are public and private keys that need to passed in PEM format.
- iv (optional) - - initialization vector, if not provided we will automatically generate one - default: nil
-
options
()
- - a Hash with additional options to control the encrypt algorithm
- transform_key_to_hex (Boolean) - - transfrom key to HEX
- return_hex (Boolean) - - return HEX encrypted string instead of Base64 encoded
- pad_payload_right (Integer) - - integer value of block length
Returns
String - Base64 encoded (RFC 4648) (or HEX if return_hex is true) encrypted string using the algorithm of your choice. Initialization Vector (iv) will be appended
Examples
{% capture payload %}
{
"key": "value",
"another_key": "another value"
}
{% endcapture %}
{{ payload | encrypt: 'aes-256-cbc', 'ThisPasswordIsReallyHardToGuessA' }} => Kkuo2eWEnTbcrtbGjAmQVMTjptS5elsgqQe-5blHpUR-ziHPI45n2wOnY30DVZGldCTNqMT_Ml0ZFiGiupKGD4ZWxVIMkdCHaq4XgiAIUew=
{{ "step=2;header.amount=10;header.paymentTypeCode=ONLINE;customer.firstName=John" | encrypt: 'aes-128-ecb', '4C6C821832AAFFF2749852CEED2FE74F', null, true, true, 32 }} => 43553EEDD9BFE36D10F99E931245CF8826903C00D235DFD300B3CC40BD263A621FC2FB9F5C3743F75D399A912AFABF92371927C6D190E0EFF19EAE9802320391FED79D92009796403EC6B426E901AB981CE53A43557C295F3D6FC9678EE0557F
end_with
Check if string ends with given substring(s)
Params
- string (String) - string to check ends with any of the provided suffixes
- suffixes (StringArray) - suffix to check
Returns
Boolean - true if string ends with a suffixes
Examples
{{ 'my_example' | end_with: 'example' }} => true
{{ 'my_example' | end_with: 'my' } => false
{% assign suffixes = ['array', 'example'] | parse_json %}
{{ 'my_example' | end_with: suffixes } => true
escape_javascript
Params
- text (String) - text to be escaped
Returns
String - escaped text
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
Creates url based on provided named parameters to the template
Params
- template (String) - URL template. Read more at https://tools.ietf.org/html/rfc6570
- params (Hash) - hash with data injected into template
Returns
String - expanded URL
Examples
{% assign template = "/search/{city}/{street}" %}
{{ template | expand_url_template: city: "Sydney", street: "BlueRoad" }}
=> /search/Sydney/BlueRoad
{% assign template = "/search{?city,street}" %}
{{ template | expand_url_template: city: "Sydney", street: "BlueRoad" }}
=> /search?city=Sydney&street=BlueRoad
extract_url_params
Extracts named parameters from the url
Params
- url (String) - URL with params to extract
- templates (StringArray) - URL template, works also with array of templates. Read more at https://tools.ietf.org/html/rfc6570
Returns
Hash - hash with extracted params
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"}
force_encoding
The filter returns a string with the encoding changed to the one specified by the 'encoding' parameter. The filter does not change the string itself (its representation in memory) but changes how the underlying bytes in the string are interpreted to determine which characters they encode
Params
- text (String) - input string whose encoding we want modified
Returns
String - input string with encoding modified to the one specified by the encoding parameter
Examples
{{ 'John arrived_foo' | force_encoding: "ISO-8859-1" }}
format_number
Params
- number (Untyped) - string (numberlike), integer or float to format
-
options
(Hash)
- formatting options
- locale (String) - Sets the locale to be used for formatting (defaults to current locale).
- precision (Number) - Sets the precision of the number (defaults to 3).
- significant (String) - If true, precision will be the number of significant_digits. If false, the number of fractional digits (defaults to false).
- separator (String) - Sets the separator between the fractional and integer digits (defaults to ".").
- delimiter (String) - Sets the thousands delimiter (defaults to "").
- strip_insignificant_zeros (Boolean) - If true removes insignificant zeros after the decimal separator (defaults to false).
Returns
String - formatted number
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
fractional_to_amount
Converts currency in fractional to whole amount. For example, convert cents to USD.
Params
- amount (IntegerString) - fractional amount
- currency (String) - currency to be used - default: 'USD'
Returns
Number - converted fractional amount
Examples
{{ 10.50 | fractional_to_amount: 'USD' }} => 10
{{ 1050 | fractional_to_amount: 'JPY' }} => 1050
hash_add_key (aliases: add_hash_keyassign_to_hash_key)
Params
- hash (Hash)
- key (String)
- value (Untyped)
Returns
Hash - hash with added key
Examples
{% liquid
assign accountants = "Angela,Kevin,Oscar" | split: ","
assign management = "David,Jan,Michael" | split: ","
assign company = '{}' | parse_json
assign company = company | hash_add_key: "name", "Dunder Mifflin"
assign company = company | hash_add_key: "accountants", accountants
assign company = company | hash_add_key: "management", management
%}
{{ company }} => {"name"=>"Dunder Mifflin", "accountants"=>["Angela", "Kevin", "Oscar"], "management"=>["David", "Jan", "Michael"]}
hash_delete_key (aliases: delete_hash_keyremove_hash_key)
Params
- hash (Hash)
- key (String)
Returns
Untyped - value which was assigned to a deleted key. If the key did not exist in the first place, null is returned.
Examples
{% liquid
assign hash = '{ "a": "1", "b": "2"}' | parse_json
assign a_value = hash | hash_delete_key: "a"
%}
{{ a_value }} => "1"
{{ hash }} => { "b": "2" }
hash_diff
Generates a list of additions (+), deletions (-) and changes (~) from given two ojects.
Params
- hash1 (Hash)
- hash2 (Hash)
Returns
Array - array containg the difference between two hashes
Examples
{% liquid
assign a = '{ "a": 1, "c": "5 ", "d": 6, "e": { "f": 5.12 } }' | parse_json
assign b = '{ "b": 2, "c": "5", "d": 5, "e": { "f": 5.13 } }' | parse_json
%}
{{ a | hash_diff: b }} => [["-","a",1],["~","c","5 ","5"],["~","d",6,5],["~","e.f",5.12,5.13],["+","b",2]]
{{ a | hash_diff: b, strip: true }} => [["-","a",1],["~","d",6,5],["~","e.f",5.12,5.13],["+","b",2]]
hash_dig (aliases: dig)
Params
- hash (Hash)
- keys (Array) - comma separated sequence of string keys to dig down the hash
Returns
Untyped - Extracted nested value specified by the sequence of keys by calling dig at each step, returning null if any intermediate step is null.
Examples
{% parse_json user_json %}
{
"name": {
"first": "John"
"last": "Doe"
}
}
{% endparse_json %}
{{ user_json | hash_dig: "name", "first" }} => "John"
hash_keys
Params
- hash (Hash) - input hash
Returns
Array
Examples
{% liquid
assign data = null | hash_merge: foo: 'fooval', bar: 'barval'
%}
{{ data | hash_keys }} => ["foo", "bar"]
hash_merge
Params
- hash1 (Hash)
- hash2 (Hash)
Returns
Hash - new hash containing the contents of hash1 and the contents of hash2. On duplicated keys we keep value from hash2
Examples
{% liquid
assign a = '{"a": 1, "b": 2 }' | parse_json
assign b = '{"b": 3, "c": 4 }' | parse_json
assign new_hash = a | hash_merge: b
%}
{{ new_hash }} => { "a": 1, "b": 3, "c": 4 }
{% liquid
assign a = '{"a": 1}' | parse_json
assing a = a | hash_merge: b: 2, c: 3
%}
{{ a }} => { "a": 1, "b": 2, "c": 3 }
hash_sort
Params
- input (Hash) - Hash to be sorted
Returns
Hash - Sorted hash
Examples
{% assign hash1 = '{"key2": "value2", "key1": "value1"}' | parse_json %}
{{ hash1 | hash_sort }} => {"key1": "value1", "key2": "value2"}
{% assign hash1 = '{"a": 1, "c": 2, "b": 3}' | parse_json %}
{{ hash1 | hash_sort }} => {"a": 1, "b": 3, "c": 2}
hash_values
Params
- hash (Hash) - input hash
Returns
Array
Examples
{% liquid
assign data = null | hash_merge: foo: 'fooval', bar: 'barval'
%}
{{ data | hash_values }} => ["fooval", "barval"]
hcaptcha
Params
- params (Hash) - params sent to the server
Returns
Boolean - whether the parameters are valid hcaptcha verification parameters
Examples
{{ context.params | hcaptcha }} => true
html_safe
Params
- text (String)
- options (Hash) - set raw_text to true to stop it from unescaping HTML entities - default: {}
Returns
String - string that can be rendered with all HTML tags, by default all variables are escaped.
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
{{ 'abc " def' | html_safe: raw_text: true }} => 'abc " def'
{{ 'abc " def' | html_safe: raw_text: false }} => 'abc " def'
html_to_text
Params
- html (String) - html to be converted to text
-
options
(Hash)
- optional. Default root_element: null, remove_nodes: 'script, link, style', replace_newline: ' '
- root_element (String) - css selector of node which content should be returned, default is null
- remove_nodes (String) - CSS selector of nodes that should be ignored, default is 'script, link, style'
- replace_newline (String) - specifies a character to be used to replace newlines, default is ' ' (new lines will be converted to space)
Returns
String - text without any html tags
Examples
{{ '<h1>Hello <a href="#">world</a></h1>' }} => 'Hello world'
humanize
Params
- key (String) - input string to be transformed
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.).
Examples
{{ 'car_model' | humanize }} => 'Car model'
{{ 'customer_id' | humanize }} => 'Customer'
is_date_before (aliases: date_before)
Params
- first_time (StringIntegerDateTime) - time to compare to the second parameter
- second_time (StringIntegerDateTime) - time against which the first parameter is compared to
Returns
Boolean - returns true if the first time is lower than the second time
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
Params
- time (StringIntegerDateTime) - time object, can also be a string
- now (StringIntegerDateTime) - sets the time from which operation should be performed
Returns
Boolean - true if time passed is in the past, false otherwise
Examples
{{ '2010-01-01' | is_date_in_past }} => true
{{ '3000-01-01' | is_date_in_past }} => false
is_email_valid
Params
- email (String) - String containing potentially valid email
Returns
Boolean - whether or not the argument is a valid email
Examples
{% assign valid = '[email protected]' | is_email_valid %}
valid => true
{% assign valid = 'john@' | is_email_valid %}
valid => false
is_json_valid
Params
- text (String) - String containing potentially valid JSON
Returns
Boolean - whether or not the argument is a valid JSON
Examples
{% assign valid = '{ "name": "foo", "bar": {} }' | is_json_valid %}
valid => true
{% assign valid = '{ "foo" }' | is_json_valid %}
valid => false
is_parsable_date
Params
- object (Untyped) - object that can be a date
Returns
Boolean - whether the parameter can be parsed as a date
Examples
{{ '2021/2' | is_parsable_date }} => true
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.
Params
- token (String) - encrypted token generated via the temporary_token GraphQL property
- user_id (Number) - id of the user who generated the token
Returns
Boolean - returns true if the token has not expired and was generated for the given user, false otherwise
Examples
{% token = '1234' %}
{{ token | is_token_valid: context.current_user.id }} => false
json (aliases: to_json)
Params
- object (Untyped) - object you want a JSON representation of
Returns
String - JSON formatted string containing a representation of object.
Examples
{{ user | json }} => {"name":"Mike","email":"[email protected]"}
jwe_encode (aliases: jwe_encode_rc)
Params
- json (String) - JSON body string that will be encypted
- key (String) - Public key
- alg (required) - - Key Management Algorithm used to encrypt or determine the value of the Content Encryption Key. Valid options: Single Asymmetric Public/Private Key Pair RSA1_5 RSA-OAEP RSA-OAEP-256 Two Asymmetric Public/Private Key Pairs with Key Agreement ECDH-ES ECDH-ES+A128KW ECDH-ES+A192KW ECDH-ES+A256KW Symmetric Password Based Key Derivation PBES2-HS256+A128KW PBES2-HS384+A192KW PBES2-HS512+A256KW Symmetric Key Wrap A128GCMKW A192GCMKW A256GCMKW A128KW A192KW A256KW Symmetric Direct Key (known to both sides) dir
- enc (required) - - Encryption Algorithm used to perform authenticated encryption on the plain text using the Content Encryption Key. Valid options: A128CBC-HS256 A192CBC-HS384 A256CBC-HS512 A128GCM A192GCM A256GCM
Returns
String
jwt_decode
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 - default: ''
- verify_signature (Boolean) - default true, for testing and debugging can remove verifying the signature - default: true
- jwks (Hash) - JWK is a structure representing a cryptographic key. Currently only supports RSA public keys. 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: nil
Returns
Hash - result of decoding JWT token
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
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: {}
Returns
String - JWT token encrypted using the algorithm of your choice
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 %}
localize (aliases: l)
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
Returns
String, nil - formatted representation of the passed parsable time
Examples
{{ '2010-01-01' | localize }} => 'January 01, 2010'
{{ 'in 14 days' | localize: 'long', '', '2011-03-15' }} => 'March 14, 2011'
map
Params
- object (Array) - 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
Returns
Array - array which includes all values for a given key
Examples
{% assign objects = '[{"id":1,"name":"foo","label":"Foo"},{"id":2,"name":"bar","label":"Bar"}]' | parse_json %}
{{ objects | map: 'name' }} => ['foo', 'bar']
markdown (aliases: markdownify)
Params
- text (String) - text using markdown syntax
- options (String) - string representing a JSON object with options for the sanitizer - default: SANITIZE_DEFAULT
- extra_options (String) - string representing a JSON object with additional options for the sanitizer which can override the options param; pass nil for the options param to use the default options which extra_options could then override - default: {}
Returns
String - processed text with markdown syntax changed to sanitized HTML. We allow only safe tags and attributes by default. We also automatically add `rel=nofollow` to links. Default configuration is: { "elements": ["a","abbr","b","blockquote","br","cite","code","dd","dfn","dl","dt","em","i","h1","h2","h3","h4","h5","h6","img","kbd","li","mark","ol","p","pre","q","s","samp","small","strike","strong","sub","sup","time","u","ul","var"], "attributes":{ "a": ["href"], "abbr":["title"], "blockquote":["cite"], "img":["align","alt","border","height","src","srcset","width"], "dfn":["title"], "q":["cite"], "time":["datetime","pubdate"] }, "add_attributes": { "a" : {"rel":"nofollow"} }, "protocols": { "a":{"href":["ftp","http","https","mailto","relative"]}, "blockquote": {"cite": ["http","https","relative"] }, "q": {"cite": ["http","https","relative"] }, "img": {"src": ["http","https","relative"] } } }
Examples
{{ '**Foo**' | markdown }} => '<b>Foo</b>'
{{ '**Foo**' | markdown }} => '<b>Foo</b>'
{{ '# Foo' | markdown }} => '<h1>Foo</h1>'
Automatically add rel=nofollow to links
{{ '[Foo link](https://example.com)' | markdown }} => '<p><a href="https://example.com" rel="nofollow">Foo link</a></p>'
{{ '<b>Foo</b>' | markdown }} => '<b>Foo</b>'
Tags not enabled by default are removed
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown }} => 'Foo'
Attributes not enabled by default are removed
{{ '<div class="hello" style="font-color: red; font-size: 99px;">Foo</div>' | markdown: '{ "elements": [ "div" ] }' }} => '<div>Foo</div>' # @example
Specify custom tags with attributes
Using extra_options to override options
{% assign link1 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value", "rel": null } } }' %}
{{ link1 }} => <p><a href="https://example.com" custom_attr="custom_value">Foo link</a></p>
{% assign link2 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": {} } }' %}
{{ link2 }} => <p><a href="https://example.com">Foo link</a></p>
{% assign link3 = '[Foo link](https://example.com)' | markdown: nil, '{ "add_attributes": { "a": { "custom_attr": "custom_value" } } }' %}
{{ link3 }} => <p><a href="https://example.com" rel="nofollow" custom_attr="custom_value">Foo link</a></p>
{% assign link4 = '[Foo link](https://example.com)' | markdown %}
{{ link4 }} => <p><a href="https://example.com" rel="nofollow">Foo link</a></p>
matches
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
Returns
Boolean - whether the given string matches the given regular expression; returns null if
Examples
{{ 'foo' | matches: '[a-z]' }} => true
pad_left
Params
- str (String) - string to pad
- count (Number) - minimum length of output string
- symbol (String) - string to pad with - default: ' '
Returns
String - returns string padded from left to the length of count with the symbol character
Examples
{{ 'foo' | pad_left: 5 }} => ' foo'
{{ 'Y' | pad_left: 3, 'X' }} => 'XXY'
parameterize
Params
- text (String) - input string to be 'parameterized'
- separator (String) - string to be used as separator in the output string; default is '-' - default: '-'
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 '-';
Examples
{{ 'John arrived_foo' | parameterize }} => 'john-arrived_foo'
parse_csv (aliases: parse_csv_rc)
Params
- input (String) - CSV
-
options
(Hash)
- parse csv options
- convert_to_hash (Boolean) - Returns [Array of Objects]
Returns
Array of Arrays - Array
Examples
{% liquid
assign csv = "name,description\nname-1,description-1\nname-2,description-2\n"
{{ csv | parse_csv }} => [['name', 'description'], ['name-1', 'description-1'], ['name-2', 'description-2']]
{{ csv | parse_csv: convert_to_hash: true }} => [{name: 'name-1', description: 'description-1'}, {name: 'name-2', description: 'description-2'}]
%}
parse_json (aliases: to_hash)
Params
- object (Untyped) - String containing valid JSON
- options (Hash) - set to raw_text true to stop it from unescaping HTML entities - default: {}
Returns
Hash - Hash created based on JSON
Examples
{% liquid
assign text = '{ "name": "foo", "bar": {} }'
assign object = text | parse_json
%}
{{ object.name }} => 'foo'
{{ '{ "key": "abc " def" }' | parse_json: raw_text: false }} => { "key": 'abc " def' }
{{ '{ "key": "abc " def" }' | parse_json: raw_text: true }} => { "key": 'abc " def' }
parse_xml (aliases: xml_to_hash)
Params
- xml (String) - String containing valid XML
- options (Hash) - attr_prefix: use '@' for element attributes, force_array: always try to use arrays for child elements - default: {}
Returns
Hash - Hash created based on XML
Examples
{% liquid
assign text = '<?xml version="1.0" encoding="UTF-8"?><letter><title maxlength="10"> Quote Letter </title></letter>'
assign object = text | parse_xml
%}
{{ object }} => '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}'
pluralize
Use either singular or plural version of a string, depending on provided count
Params
- string (String) - string to be pluralized
- count (Number) - optional count number based on which string will be pluralized or singularized - default: 2
Returns
String - pluralized version of the input string
Examples
{{ 'dog' | pluralize: 1 }} => 'dog'
{{ 'dog' | pluralize: 2 }} => 'dogs'
pricify
Params
- amount (NumericString) - amount to be formatted
- currency (String) - currency to be used for formatting - default: 'USD'
- options (Hash) - optional. Default no_cents_if_whole: true - default: {}
Returns
String - formatted price using global price formatting rules
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
{{ 1 | pricify: "USD", no_cents_if_whole: false }} => $1.00
pricify_cents
Adds currency symbol and proper commas. It is used to showing prices to people.
Params
- amount (NumericString) - amount in cents to be formatted
- currency (String) - currency to be used for formatting - default: 'USD'
Returns
String - formatted price using the global price formatting rules
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
Params
- hash (Hash) - hash to be "querified"
Returns
String - a query string
Examples
{{ hash }} => { 'name' => 'Dan', 'id' => 1 }
{{ hash | querify }} => 'name=Dan&id=1'
random_string
Params
- length (Int) - how many random characters should be included; default is 12 - default: 12
Returns
String - returns a random alphanumeric string of given length
Examples
{{ 10 | random_string }} => '6a1ee2629'
raw_escape_string
Params
- value (String) - input string to be HTML-escaped
Returns
String - HTML-escaped input string; returns a string with its HTML tags visible in the browser
Examples
{{ 'foo<b>bar</b>' | raw_escape_string }} => 'foo&lt;b&gt;bar&lt;/b&gt;'
regex_matches
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: ''
Returns
Array - 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"]]
Examples
To retrieve the URL from a meta tag see the example below:
{% liquid
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]
echo image_path
endif
%}
replace_regex
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
Returns
String - string with regexp pattern replaced by replacement text
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:
{% liquid
assign hash = '{}' | parse_json
assign hash = hash | hash_add_key: 'ooooo', 'bbbbb'
assign hash = hash | hash_add_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"
Matches group:
{% assign array = "item 1,item 2,item 3,item 4" | split: "," %}
{{ array | join: ", " | replace_regex: "([^,]+),([^,]+)$", "\1, &\2" }} => item 1, item 2, item 3, & item 4
sanitize
Params
- input (String) - potential malicious html, which you would like to sanitize
- options () - Options to configure which elements and attributes are allowed, example: { "elements": ["a", "b", "h1"], "attributes": { "a": ["href"] } } - default: SANITIZE_DEFAULT
- whitelist_tags (Array) - deprecated; do not use - default: nil
Returns
String - Sanitizes HTML input. If you want to allow any HTML, use html_safe filter. By default we allow only safe html tags and attributes. We also automatically add `rel=nofollow` to links. Default configuration is: { "elements": ["a","abbr","b","blockquote","br","cite","code","dd","dfn","dl","dt","em","i","h1","h2","h3","h4","h5","h6","img","kbd","li","mark","ol","p","pre","q","s","samp","small","strike","strong","sub","sup","time","u","ul","var"], "attributes":{ "a": ["href"], "abbr":["title"], "blockquote":["cite"], "img":["align","alt","border","height","src","srcset","width"], "dfn":["title"], "q":["cite"], "time":["datetime","pubdate"] }, "add_attributes": { "a" : {"rel":"nofollow"} }, "protocols": { "a":{"href":["ftp","http","https","mailto","relative"]}, "blockquote": {"cite": ["http","https","relative"] }, "q": {"cite": ["http","https","relative"] }, "img": {"src": ["http","https","relative"] } } }
Examples
{% capture link %}
<a href="javascript:prompt(1)">Link</a>
{% endcapture %}
{{ link | sanitize }} => <a href="">Link</a>
{% assign whitelist_attributes = 'target' | split: '|' %}
{{ link | sanitize: whitelist_attributes }} => <a href="">Link</a>
scrub
Scrubs invalid characters and sequences from the input string, in the given encoding (by default UTF-8)
Params
- text (String) - string to be scrubbed
- source_encoding (String) - encoding of the input string, default UTF-8 - default: "UTF-8"
- final_encoding (String) - encoding of the output string, default UTF-8 - default: "UTF-8"
Returns
String - Returns a string scrubbed of invalid characters and sequences; to be used when data is coming from external sources like APIs etc.
Examples
{% assign scrubbed = "Hello W�orld" | scrub %}
{{ scrubbed }} => "Hello World"
slugify
Params
- text (String) - input string to be 'slugified'
Returns
String - replaces special characters in a string so that it may be used as part of a 'pretty' URL;
Examples
{{ 'John arrived_foo' | slugify }} => 'john-arrived-foo'
start_with
Check if string starts with given substring(s)
Params
- string (String) - string to check if starts with any of the provided prefixes
- prefixes (StringArray) - prefix(es) to check
Returns
Boolean - true if string starts with a prefix
Examples
{{ 'my_example' | start_with: 'my' }} => true
{{ 'my_example' | start_with: 'example' } => false
{% assign prefixes = ['array', 'example'] | parse_json %}
{{ 'my_example' | start_with: prefixes } => true
strftime
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
Returns
String - formatted representation of the time object; the formatted representation will be based on what the format parameter specifies
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
strip_liquid
Params
- text (String) - text from which to strip liquid
Returns
String - input parameter without liquid
Examples
{{ 'Hello! {% comment %}This is a comment!{% endcomment %}' | strip_liquid }} => "Hello! This is a comment!"
time_diff
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 (Number) - defines rounding after comma; default is 3 - default: 3
Returns
Number - duration between start and finish in unit; default is ms (milliseconds)
Examples
{% assign result = 'now' | time_diff: 'in 5 minutes', 'd' %}
{{ result }}
{% assign minutes_until_date = 'now' | time_diff: '2026-10-08 00:00', 'm' %}
{% comment %}{% background _ = 'commands/foo', delay: minutes_until_date %} %}{% endcomment %}
titleize
Params
- text (String) - string to be processed
Returns
String - capitalizes all the words and replaces some characters in the string to create a string in title-case format
Examples
{{ 'foo bar_zoo-xx' | titleize }} => 'Foo Bar Zoo Xx'
to_csv
Params
- input (Array) - array you would like to convert to CSV
-
options
(Hash)
- csv options
- row_sep (String) - Specifies the row separator; used to delimit rows.
- col_sep (String) - Specifies the column separator; used to delimit fields.
- quote_char (String) - Specifies the quote character; used to quote fields.
- write_headers (Boolean) - Specifies whether headers are to be written.
- force_quotes (Boolean) - Specifies whether each output field is to be quoted.
- quote_empty (Boolean) - Specifies whether each empty output field is to be quoted.
- sanitize (Boolean) - Escape special chars to prevent CSV injection attacks, default true.
Returns
String - String containing CSV. If one of the array element contains separator, this element will automatically be wrapped in double quotes.
Examples
{% liquid
assign arr = '' | split: ','
assign headers = 'id,header1,header2' | split: ','
assign row1 = '1,example,value' | split: ','
assign row2 = '2,another,val2' | split: ','
assign arr = arr | array_add: headers | array_add: row1 | array_add: row2
%}
{{ arr | to_csv }} => "id","header1","header2"\n1,"example","value"\n2,"another","val2"
{{ arr | to_csv: force_quotes: true }} => "id","header1","header2"\n"1","example","value"\n"2","another","val2"
to_date
Params
- time (StringIntegerDateTime) - parsable time object to be converted to date
- now (StringIntegerDateTime) - sets the time from which operation should be performed
Returns
Date - a Date object obtained/parsed from the input object
Examples
{{ '2010-01-01 8:00:00' | to_date }} => 2010-01-01
to_mobile_number
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
Returns
String - returns mobile number in E.164 format; recommended for sending sms notifications
Examples
{{ '500 123 999' | to_mobile_number: 'PL' }} => '+48500123999'
to_positive_integer
Params
- param (Untyped) - value to be coerced to positive integer
- default (Number) - default value in case param is not valid positive integer
Returns
Number - number that is higher than 0
Examples
{{ '1' | to_positive_integer: 2 }} => 1
{{ '' | to_positive_integer: 2 }} => 2
to_time
Params
- time (StringIntegerDateTime) - a string representation of time ('today', '3 days ago', 'in 10 minutes' etc.) or a number 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
Returns
DateTime - a time object created from parsing the string representation of time given as input
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' }}
to_xml (aliases: to_xml_rc)
Params
- object (Hash) - hash object that will be represented as xml
- options (Hash) - attr_prefix: use '@' for element attributes - default: {}
Returns
String - String containing XML
Examples
{% liquid
assign object = '{"letter":[{"title":[{"maxlength":"10","content":" Quote Letter "}]}]}' | parse_json
assign xml = object | to_xml
%}
{{ object }} => '<letter> <title maxlength="10"> Quote Letter </title> </letter>'
translate (aliases: t)
Params
- key (String) - translation key
-
options
(Hash)
- values passed to translation string
- locale (Untyped) - Enforces using specified locale instead of value provided via `?language=<locale>`
- default (Untyped) - Specifies the default for a scenario when translation is missing. If fallback not set to true, system will automatically try to load english translation first
- fallback (String) - specify whether the system should try to fallback to english if translation is missing for the current locale
Returns
String - Translation value taken from translations YML file for the key given as parameter. The value is assumed to be html safe, please use `t_escape` if you provide unsafe argument which can potentially include malicious script.
Examples
{{ 'beer' | translate }} => 'cerveza'
{{ 'beer' | t }} => 'cerveza'
{{ 'drinks.alcoholic.beer' | t }} => 'piwo'
{{ 'non_existing_translation' | t: default: 'Missing', fallback: false }} => 'Missing'
{{ 'user-greeting' | t: username: 'Mike' }} => 'Hello Mike!'
translate_escape (aliases: t_escape)
Escapes unsafe arguments passed to the translation and then returns its value
Params
- key (String) - translation key
- options (Hash) - values passed to translation string - default: {}
Returns
String - translation value taken from translations YML file for the key given as parameter
Examples
en.yml
en:
user-greeting: Hello %{username}
{{ 'user-greeting' | t_escape: username: '<script>alert("hello")</script>Mike' }}
=> will not evaluate the script, it will print out:
Hello <script>alert("hello")</script>Mike
type_of
Params
- variable (Untyped) - Variable whose type you want returned
Returns
String - Type of the variable parameter
Examples
{% assign variable_type = '{ "name": "foo", "bar": {} }' | parse_json | type_of %}
{{ variable_type }}
unescape_javascript
Params
- text (String) - text to be unescaped
Returns
String - unescaped javascript text
Examples
{% capture 'js' %}
<script>
let variable = "\t some text\n";
let variable2 = 'some text 2';
let variable3 = `some text`;
let variable4 = `We love ${variable3}.`;
</script>
{% endcapture %}
This will return the text to its original form:
{{ js | escape_javascript | unescape_javascript }}
url_to_qrcode_svg
Params
- url (String) - URL to be encoded as QR code
-
options
(Hash)
- optional. Defaults: color: "000", module_size: 11, shape_rendering: "crispEdges", viewbox: false
- shape_rendering (String) - Possible options: auto | optimizeSpeed | crispEdges | geometricPrecision ; default is crispEdges
- viewbox (Boolean) - Replace the `svg.width` and `svg.height` attribute with `svg.viewBox` to allow CSS scaling , default false
- standalone (Boolean) - Whether to make this a full SVG file, or only an svg to embed in other svg, default true
- svg_attributes (Hash) - An optional hash of custom <svg> attributes. Existing attributes will remain. (default {})
- color (String) - Default is "000"
- module_size (Number) - Default is 11
Returns
String - either `<path ...>...</path>` or `<svg ...>...</svg>` depending on standalone flag
Examples
<svg width="319" height="319">{{ 'https://example.com' | url_to_qrcode_svg, color: '000', module_size: 11 }}</svg> => <svg width="319" height="319"><path>...</path></svg>
useragent
Params
- useragent_header (String) - browser user agent from the request header
Returns
Hash - parsed browser user agent information
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
Params
- _dummy (String) - parameter will be ignored - default: nil
Returns
String - Universally unique identifier v4
Examples
{{ '' | uuid }} => "2d931510-d99f-494a-8c67-87feb05e1594"
{% assign id = '' | uuid %}
{{ id }} => "b12bd15e-4da7-41a7-b673-272221049c01"
verify_access_key
Params
- access_key (String) - can be obtained in Partner Portal
Returns
Boolean - check if key is valid
Examples
{% assign access_key = '12345' %}
{{ access_key | verify_access_key }} => true
video_params
Params
- url (String) - URL to a video on the internet
Returns
Hash - metadata about video
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
Params
- url (String) - URL to a video on the internet - default: ''
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
www_form_encode_rc
Params
- object (Untyped) - data object
Returns
String - This generates application/x-www-form-urlencoded data defined in HTML5 from given object.
Examples
assign object = '{"foo": "bar", "zoo": [{ "xoo": 1 }, {"xoo": 2}]}' | parse_json
assign form_data = object | www_form_encode_rc
=> "foo=bar&zoo[0][xoo]=555&zoo[1][xoo]=999",
array_include (aliases: is_included_in_array)
Checks if array includes element
Params
- array (Array) - array of elements to look into
- el (Untyped) - look for this element inside the array
Returns
Boolean - whether the array includes the element given
Examples
{% assign elements = 'a,b,c,d' | split: ',' %}
{{ elements | array_include: 'c' }} => true
asset_path
Generates relative path to an asset, including `updated` query parameter
Params
- file_path (String) - path to the asset, relative to assets directory
Returns
String - relative path to the physical file decorated with updated param to invalidate CDN cache. Always prefer asset_url,
Examples
{{ "valid/file.jpg" | asset_path }} => /assets/valid/file.jpg?updated=1565632488
{{ "nonexistent/file.jpg" | asset_path }} => /assets/nonexistent/file.jpg
hash_fetch (aliases: fetch)
Params
- hash (Hash) - input hash to be traversed
- key (String) - key to be fetched from hash branch
Returns
Untyped
Examples
{% parse_json users %}
[{
"name": "Jane"
}, {
"name": "Bob"
}]
{% endparse_json %}
{{ users | first | hash_fetch: "name" }} => "Jane"
new_line_to_br (aliases: nl2br)
sha1
Params
- object (String) - input object that you want to obtain the digest for
Returns
String - SHA1 digest of the input object
Examples
{{ 'foo' | sha1 }} => '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'